I've read a ton of articles about sagas testing, but couldn't find the solution to the problem I've ran into, maybe someone here, who is experienced enough with the topic, could help me?
Sorry for bad english, it's not my native language, I've tried my best. :)
The problem is: while trying to test saga function, which handles request to server with axios. I've mocked axios module in mock folder with a Promise, so it would always resolve successfully, but when the axios is being accessed from saga, it resolves as unsuccessful request, so my saga will always throw an action from the 'catch' block.
The real api request code:
export const fetchAddressList = address =>
axios.post("http://localhost:4000/addresses", { geocode: address });
Mocked axios module in mock folder:
export default {
post: jest.fn(() => Promise.resolve({ data: { result: [] } }))
};
The saga I'm testing:
export function* fetchAddressListSaga(action) {
try {
// this function returns an axios request promise
const { data } = yield fetchAddressList(action.addressValue);
yield put(fetchAddressListSuccess(data));
} catch (e) {
yield put(fetchAddressListFail());
}
}
My test suite:
it("should dispatch ADDRESS_LIST_FETCH_SUCCESS action when API call succeeds", async () => {
mockAxios.post.mockImplementationOnce(() =>
Promise.resolve({
data: "my custom response"
})
);
const response = await geocoderApi.fetchAddressList();
// logs response, passed with promise to mockImplementationOnce
// which means that the imported axios module is mocked
console.log(response);
const requestSaga = fetchAddressListSaga(action);
requestSaga.next();
const requestSagaResult = requestSaga.next().value;
expect(requestSagaResult.payload.action.type).toEqual(
actionTypes.ADDRESS_LIST_FETCH_SUCCESS
);
});
Aucun commentaire:
Enregistrer un commentaire