How to mock a browser in a unit test environment?

I am trying to test the React component that uses the browserHistory of a reactive router. To provide access to browserHistory, I use the createMemoryHistory module (reactive router) as follows:

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

In the test env, I use the JSDOM library.

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

Then I try to assign the created DOM history object:

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

When rendering a component in a test environment, I get the following error:

Invariant violation: browser history requires DOM

Any idea how to overcome it?

+6
source share
1 answer

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

For instance:

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 spy and stub

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

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

0
source

All Articles