Using Jest to Mock Axios and Mock Windows.Location.Assignment

368 Views Asked by At

Some ReactJs component are using the Axios NPM library to fire off Http Posts. Using the post example from Axios, we have:

axios.post('/user', {
       firstName: 'Fred',
       lastName: 'Flintstone'
   })
   .then(function (response) {
       window.location.assign('/nextscreen');
   })
  .catch(function (error) {
    console.log(error);
  }); 

When the post has been made, the "then" is fired to move to the next page.

We are using Jest and Enzyme to unit test the Axios functionality. Furthermore, we have successfully mocked in isolation the: - Axios post using jest-mock-axios - window.location.assign method using jest mock.

However, when the "then" is fired in the Axios mock, the mocked window.location.assign method fails everytime.

Is it possible to mock both the Axios call and window.location.assign together?

I could pass in a method that wraps the window.location.assign method but that is not correct.

1

There are 1 best solutions below

0
On

Not sure if you mocked window object correctly. But you can always mock it in your jest test file just like this:

it('test', () => {
  window.location.assign = jest.fn();
  // your function that you want to test
  expect(window.location.assign).toBeCalledWith('/nextscreen');
});