How to “mock” window?

with No Comments

In testing process(jest + enzyme) of react application I had a problem with mock “window” into react component. Inside logic: some part of component is rendered by window.location.pathname.

Like this:

The main idea of component is a rendering or absence of the first button. At global space window.location.pathname = ‘/’. First of all I tried to set a new pathname through call functions assign() and replace(). But console said: Not implemented navigation (except hash changes). And the component was not completely covered with dough.

Wrong test:

Solution is to use function pushState() – insert new state into browser history, has 3 parameters: new state(JavaScript Object), title and URL. We don’t work in  browser and so we can give only URL.

Correct test:

Leave a Reply