代码之家  ›  专栏  ›  技术社区  ›  Joseph K.

嘲笑全球导航器.联机

  •  0
  • Joseph K.  · 技术社区  · 7 年前

    global.navigator.onLine 取笑反应。

    我的笑话是最新的 24.9.0

    global.navigator = {
      onLine: false,
    }
    

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

    他们似乎还回来了 true 对于 navigator.onLine

    0 回复  |  直到 7 年前
        1
  •  6
  •   Lin Du Correcter    7 年前

    你可以用 jest.spyOn(object, methodName, accessType?) onLine navigator reactjs .

    例如:

    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