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 24 beforeAll(() => { 25 // Mock XMLHttpRequest 26 originalXMLHttpRequest = global.XMLHttpRequest; 27 mockXMLHttpRequest = jest.fn(() => ({ 28 open: jest.fn(), 29 send: jest.fn(), 30 status: 200, 31 getResponseHeader: (header) => { 32 if (header === 'request_info') { 33 return 'mocked_request_info'; 34 } 35 }, 36 })); 37 global.XMLHttpRequest = mockXMLHttpRequest; 38 39 // Mock fetch 40 originalFetch = global.fetch; 41 mockFetch = jest.fn(() => 42 Promise.resolve({ 43 text: () => Promise.resolve('1000'), 44 }) 45 ); 46 global.fetch = mockFetch; 47 48 Object.defineProperty(window, 'location', { 49 value: { 50 protocol: 'https:', 51 host: 'example.com', 52 }, 53 }); 54 }); 55 afterAll(() => { 56 global.XMLHttpRequest = originalXMLHttpRequest; 57 global.fetch = originalFetch; 58 }); 59 afterEach(() => { 60 mockXMLHttpRequest.mockClear(); 61 mockFetch.mockClear(); 62 }); 63 it('SpStatisticsHttpUtilTest01', () => { 64 const serverInfo = SpStatisticsHttpUtil.getRequestServerInfo(); 65 expect(serverInfo).toBe(''); 66 }); 67 it('SpStatisticsHttpUtilTest02', async () => { 68 await SpStatisticsHttpUtil.getServerTime(); 69 expect(mockFetch).toHaveBeenCalledWith('https:///serverTime'); 70 expect(SpStatisticsHttpUtil.serverTime).toBe(0); 71 }); 72 it('SpStatisticsHttpUtilTest03', async () => { 73 SpStatisticsHttpUtil.pauseRetry = true; 74 await SpStatisticsHttpUtil.getServerTime(); 75 expect(mockFetch).not.toHaveBeenCalled(); 76 expect(SpStatisticsHttpUtil.serverTime).toBe(1000); 77 }); 78});