How to mock browserHistory in unit test environment?

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/


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)

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