简体   繁体   中英

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',
  }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM