therewillbecode
therewillbecode

Reputation: 7180

How to test React-Router navigation through call to history.push using Jest?

How should I test the function below that programmatically navigates me to a given page in Jest?

function someAction() {
  history.push('/home');

  return {
    type: 'NAVIGATE_HOME',
  }
}

Upvotes: 1

Views: 905

Answers (1)

Lin Du
Lin Du

Reputation: 102672

Using jest.mock(moduleName, factory, options) to mock history module and history.push method. Here is unit test solution:

action.ts:

import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

export function someAction() {
  history.push('/home');

  return {
    type: 'NAVIGATE_HOME',
  };
}

action.test.ts:

import { someAction } from './action';
import { createBrowserHistory, History } from 'history';

jest.mock('history', () => {
  const mHistory = ({ push: jest.fn() } as any) as History;
  return {
    createBrowserHistory: jest.fn(() => mHistory),
  };
});
const mCreateBrowserHistory = createBrowserHistory as jest.MockedFunction<typeof createBrowserHistory>;

describe('48146038', () => {
  it('should pass', () => {
    const mHistory = mCreateBrowserHistory();
    const actual = someAction();
    expect(actual).toEqual({ type: 'NAVIGATE_HOME' });
    expect(createBrowserHistory).toBeCalledTimes(2);
    expect(mHistory.push).toBeCalledWith('/home');
  });
});

unit test result with coverage report:

 PASS  src/stackoverflow/48146038/action.test.ts
  48146038
    ✓ should pass (5ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |      100 |      100 |      100 |      100 |                   |
 action.ts |      100 |      100 |      100 |      100 |                   |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.748s, estimated 9s

source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/48146038

Upvotes: 1

Related Questions