Jest模拟全局navigator.onLine

问题描述 投票:0回答:1

您如何在玩笑中模拟global.navigator.onLine

我的笑话版本是最新的24.9.0

我已经尝试过

global.navigator = {
  onLine: false,
}

并使用jest.fn().mockImplementation(() => ({onLine: false}))

他们似乎仍然为navigator.onLine返回[C0

mocking jestjs global
1个回答
0
投票
您可以使用true方法来模拟jest.spyOn()的只读属性onLine的值。

例如:

navigator

index.ts

export function main() {
  if (navigator.onLine) {
    console.log('online');
  } else {
    console.log('offline');
  }
}

index.spec.ts

单元测试结果覆盖率100%:

import { main } from './'; describe('main', () => { beforeEach(() => { jest.restoreAllMocks(); }); test('should log "online"', () => { const logSpy = jest.spyOn(console, 'log'); jest.spyOn(navigator, 'onLine', 'get').mockReturnValueOnce(true); main(); expect(logSpy).toBeCalledWith('online'); }); test('should log "offline"', () => { const logSpy = jest.spyOn(console, 'log'); jest.spyOn(navigator, 'onLine', 'get').mockReturnValueOnce(false); main(); expect(logSpy).toBeCalledWith('offline'); }); });

源代码: PASS  src/stackoverflow/58603653/index.spec.ts (10.016s)
  main
    ✓ should log "online" (14ms)
    ✓ should log "offline" (7ms)

  console.log node_modules/jest-mock/build/index.js:860
    online

  console.log node_modules/jest-mock/build/index.js:860
    offline

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        11.259s
© www.soinside.com 2019 - 2024. All rights reserved.