我正在尝试测试使用 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 或 stub 来帮助您对此进行测试。
例如:
使用 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)
关于 spy
和 stub
的更多信息
关于javascript - 如何在单元测试环境中模拟 browserHistory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38976078/