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:

const ExampleComponent= (props: Props) => (
     {window.location.pathname === '/newPathname’ &&
          <button><button/>
     }
     <button><button/>
);
export default ExampleComponent;

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:

describe(ExampleComponent testing', () => {
   test('should render correctly', () => {
       const wrapper = shallow(
           
       );
       expect(shallowToJson(wrapper)).toMatchSnapshot();

       window.history.assign(‘/newPathname’);
       const newWrapper = shallow(
           
       );
       expect(shallowToJson(newWrapper)).toMatchSnapshot();
   });
});

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:

describe(ExampleComponent testing', () => {
   test('should render correctly', () => {
       const wrapper = shallow(
           
       );
       expect(shallowToJson(wrapper)).toMatchSnapshot();

       window.history.pushState(
           {},
           '',
           '/newPathname’
       );
       const newWrapper = shallow(
           
       );
       expect(shallowToJson(newWrapper)).toMatchSnapshot();
   });
});

Leave a Reply