How to mock browserHistory in unit test environment?

10,977

Solution 1

You need to mock the browserHistory object. You can use sinon to create spies or stubs to help you test this.

For example:

With spy

const { createBrowserHistory } =  require('history');

const history = createBrowserHistory(/* ... */);

sinon.spy(history, "push");

// now you should be able to run assertions on history.push

assert(history.push.calledOnce)

More on the spy and stub

http://sinonjs.org/releases/v4.1.6/spies/

http://sinonjs.org/releases/v4.1.6/stubs/

Solution 2

The other answers are great, but they didn't work for my use case where I was simulating a button click which called browserHistory.push('/myroute').

In my case it was much easier to mock browserHistory in my test file using jest:

import { browserHistory } from 'react-router';

jest.mock('react-router', () => ({
  browserHistory: {
    push: jest.fn(),
  },
}));

...

it('pushes to browserHistory', () => {

    const renderedComponent = shallow(<Component />);

    <<< insert whatever you need to simulate the event that pushes to browserHistory >>>
    const button = renderedComponent.find('.btn');
    button.simulate('click');

    expect(browserHistory.push).toHaveBeenCalledTimes(1);
})
...

Solution 3

You can do it with jest as well:

const { createBrowserHistory } =  require('history');
const history = createBrowserHistory(/* ... */);
jest.spyOn(history, "push");

// now you should be able to run assertions on history.push
assert(history.push.calledOnce)
Share:
10,977
magos
Author by

magos

Updated on July 10, 2022

Comments

  • magos
    magos almost 2 years

    I'm trying to test React component which uses browserHistory of react-router. To ensure access to browserHistory I'm using createMemoryHistory (react-router) module like this:

    let createMemoryHistory = require('react-router/lib/createMemoryHistory');
    

    In test env I'm taking advantage of JSDOM library.

    global.document = jsdom('');
    global.window = document.defaultView;
    

    Then I'm trying to assign created history object to DOM:

    let history = createMemoryHistory();
    global.history = history;
    

    While rendering component in test environment, I'm getting following error:

    Invariant Violation: Browser history needs a DOM

    Any idea how to overcome it?