2016-08-16 90 views
6

我正在尝试使用react-router的browserHistory来测试React组件。为了确保获得browserHistory我使用createMemoryHistory(反应路由器)模块是这样的:如何在单元测试环境中模拟browserHistory?

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

在测试ENV我正在JSDOM库的优势。

然后我试图创造了历史对象分配给DOM:

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

虽然在测试环境中呈现组件,我收到以下错误:

Invariant Violation: Browser history needs a DOM

任何想法如何克服它?

+1

你必须实现一个模拟历史记录对象,并用它代替 –

+0

任何进一步的指令或代码示例? – magos

+1

您可以使用sinon/spies来嘲笑您正在使用的方法。请参阅http://sinonjs.org/ –

回答

0

您需要模拟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/

相关问题