[Vuejs]-Vuex test with jest throw error even if the function in the store execute well

0👍

A router or location shouldn’t be used as is in tests because Jest uses fake browser environment. They should be mocked in unit tests as they result in side effects.

The error means that location.reload is not implemented in JSDOM, and it couldn’t be implemented in a reasonable way because tests doesn’t run in browser window.

It should be:

jest.spyOn(location, 'reload');
store.commit("toggleAuth");
expect(store.state.userLoggedIn).toBe(true);
expect(location.reload).toBeCalledTimes(1);

This should be used together with jest.restoreAllMocks and jest.clearAllMocks or their configuration counterparts.

Leave a comment