如何在单元测试环境中模拟 browserHistory?

How to mock browserHistory in unit test environment?

我正在尝试测试使用 react-router 的 browserHistory 的 React 组件。为了确保访问 browserHistory,我正在使用 createMemoryHistory (react-router) 模块,如下所示:

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

在测试环境中,我正在利用 JSDOM 库。

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

然后我试图将创建的历史对象分配给 DOM:

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

在测试环境中渲染组件时,出现以下错误:

Invariant Violation: Browser history needs a DOM

知道如何克服它吗?

您需要模拟 browserHistory 对象。您可以使用 sinon 创建间谍或存根来帮助您进行测试。

例如:

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)

更多关于 spystub

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

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

您也可以使用 jest 来完成:

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)

其他答案很好,但它们不适用于我模拟按钮点击的用例,它调用了 browserHistory.push('/myroute')

在我的例子中,使用 jest 在我的测试文件中模拟 browserHistory 更容易:

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