1/*
2 * Copyright (C) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import { SpStatisticsHttpUtil } from '../../../src/statistics/util/SpStatisticsHttpUtil';
17
18describe('SpStatisticsHttpUtil Test', () => {
19  let originalXMLHttpRequest;
20  let mockXMLHttpRequest;
21  let originalFetch;
22  let mockFetch;
23  let originalXMLHttp;
24  let mockXMLHttp;
25
26  beforeAll(() => {
27    // Mock XMLHttpRequest
28    originalXMLHttpRequest = global.XMLHttpRequest;
29    mockXMLHttpRequest = jest.fn(() => ({
30      open: jest.fn(),
31      send: jest.fn(),
32      status: 200,
33      getResponseHeader: (header) => {
34        if (header === 'request_info') {
35          return 'mocked_request_info';
36        }
37      },
38    }));
39
40    // Mock fetch
41    originalFetch = global.fetch;
42    mockFetch = jest.fn(() =>
43      Promise.resolve({
44        text: () => Promise.resolve('1000'),
45      })
46    );
47    global.fetch = mockFetch;
48
49    Object.defineProperty(window, 'location', {
50      value: {
51        protocol: 'https:',
52        host: 'example.com',
53      },
54    });
55  });
56  afterAll(() => {
57    global.XMLHttpRequest = originalXMLHttpRequest;
58    global.fetch = originalFetch;
59    global.XMLHttp = originalXMLHttp 
60  });
61  afterEach(() => {
62    mockXMLHttpRequest.mockClear();
63    mockFetch.mockClear();
64  });
65  it('SpStatisticsHttpUtilTest01', () => {
66    const serverInfo = SpStatisticsHttpUtil.getRequestServerInfo();
67    expect(serverInfo).toBe('');
68  });
69  it('SpStatisticsHttpUtilTest02', async () => {
70    await SpStatisticsHttpUtil.getServerTime();
71    expect(mockFetch).toHaveBeenCalledWith('https:///serverTime');
72    expect(SpStatisticsHttpUtil.serverTime).toBe(0);
73  });
74  it('SpStatisticsHttpUtilTest03', async () => {
75    SpStatisticsHttpUtil.pauseRetry = true;
76    await SpStatisticsHttpUtil.getServerTime();
77    expect(mockFetch).not.toHaveBeenCalled();
78    expect(SpStatisticsHttpUtil.serverTime).toBe(1000);
79  });
80});