I'm new into using files with .spec.js suffix to test files with Jest, so hope it's not a stupid question. I didn't found anything through Google Stackoverflow research.
I would like to check an if else condition containing a new window.location using jest.
Here is my file.ts
export const loadBSection = (bSectionId: string) => async (
dispatch: Dispatch,
getState: GetState,
{ bSectionApi }: Deps,
) => {
try {
...
} catch (e) {
dispatch(setBSectionErrorMessage(e.message));
if (e.response.status === 404) {
window.location.href = '/page-not-found.html';
}
}
};
My file.spec.ts
it('should .. and forward to a 404 page', async () => {
...
expect(store.getActions()).toEqual([setBSectionLoading(true), setBSectionErrorMessage(errorMessage)]);
// TODO what is expected here?
});
Do you have any ideas?
As I'm new to this, maybe you have some sources for deep dives?
I used: https://create-react-app.dev/docs/running-tests/ as an intro. Do you have other resources which are helpful to find some documentation in the future?
CodePudding user response:
An idea I had but not sure if it works
Object.defineProperty(window.location, 'href', {
writable: true,
value: '/page-not-found.html',
});
CodePudding user response:
It's solved!
So it was useful to set response
optional so that other errors get catched as well. Furthermore it's easier to mock functions, so I changed window.location.href
to window.location.assign(url)
.
Makes the same but easier for testing.
file.ts
catch (e) {
dispatch(setBSectionErrorMessage(e.message));
if (e.response?.status === 404) {
window.location.assign('/page-not-found.html');
}
}
file.spec.ts
I'm creating error
and errorMessage
inside of the test method. Here you can see how an error object can be assembled with a status code as a response:
it('should navigate to /page-not-found.html ...', async () => {
const bSectionIdMock = '123';
const error = Object.assign((new Error(), { response: { status: 404 } }));
bSectionApi.bSectionsBSectionIdGet.mockRejectedValue(error);
window.location.assign = jest.fn();
await store.dispatch(loadBSection(bSectionIdMock));
expect(window.location.assign).toHaveBeenCalledWith('/page-not-found.html');
});