Jest 模拟全局 navigator.onLine

Jos*_* K. 2 global mocking jestjs

你如何global.navigator.onLine在 React 中开玩笑。

我的笑话版本是最新的 24.9.0

我试过了

global.navigator = {
  onLine: false,
}
Run Code Online (Sandbox Code Playgroud)

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

他们仍然似乎回到truenavigator.onLine

sli*_*wp2 12

您可以使用jest.spyOn(对象,方法名,存取类型?)方法来嘲笑只读属性的值onLinenavigator。此外,它与 UI 库无关reactjs

从 Jest 22.1.0+ 开始, jest.spyOn 方法接受一个可选的第三个 accessType 参数,它可以是“get”或“set”,这在你想分别监视 getter 或 setter 时被证明是有用的。

例如:

index.ts

export function main() {
  if (navigator.onLine) {
    console.log('online');
  } else {
    console.log('offline');
  }
}
Run Code Online (Sandbox Code Playgroud)

index.spec.ts

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');
  });
});
Run Code Online (Sandbox Code Playgroud)

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

 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
Run Code Online (Sandbox Code Playgroud)

源代码:https : //github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58603653