Jest mock global navigator.onLine

Viewed 2160

How do you mock global.navigator.onLine in jest for React.

My version of jest is the latest 24.9.0

I've tried

global.navigator = {
  onLine: false,
}

and using jest.fn().mockImplementation(() => ({onLine: false}))

They still seem to return true for navigator.onLine

1 Answers

You can use jest.spyOn(object, methodName, accessType?) method to mock the value of the read-only property onLine for navigator. Besides, it's nothing related about UI library reactjs.

Since Jest 22.1.0+, the jest.spyOn method takes an optional third argument of accessType that can be either 'get' or 'set', which proves to be useful when you want to spy on a getter or a setter, respectively.

For example:

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

Unit test result with 100% coverage:

 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

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58603653

Related