笑话模拟全局导航器.onLine

时间:2019-10-29 08:26:39

标签: mocking jestjs global

如何在玩笑中嘲笑global.navigator.onLine

我开玩笑的版本是最新的24.9.0

我尝试过

global.navigator = {
  onLine: false,
}

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

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

1 个答案:

答案 0 :(得分:0)

您可以使用jest.spyOn(object, methodName, accessType?)方法来模拟onLine的只读属性navigator的值。 此外,它与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');
  }
}

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');
  });
});

覆盖率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

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