I will test my redux-sagas, and stuck by mocking my api requests. The scenario is like this:
I have a GraphQL API and each request is capsuled (axios) in a requestApiUtil.
like
/path/api/sampleOneApiRequest.js
import { requestApi } from 'utils';
export const sampleOneApiRequest = ({ arg1 }) => requestApi.query(`
sampleData {
id
}
`)
/path/api/sampleTwoApiRequest.js
import { requestApi } from 'utils';
export const sampleTwoApiRequest = ({ arg1 }) => requestApi.query(`
otherSampleData {
id
}
`)
/path/api/index.js
export * from './sampleOneApiRequest';
export * from './sampleTwoApiRequest';
the saga that i like to test, looks like this
/path/redux/saga/sampleSaga/sampleSaga.js
import { all, put } from 'redux-saga/effects';
import { successAction, failureAction } from 'path/redux/action';
import { sampleOneApiRequest, sampleTwoApiRequest } from 'path/api';
export function* sampleSaga({ payload }) {
const switch = payload ? payload.switch : false;
try {
let response;
if (switch) {
response = (yield sampleOneApiRequest());
} else {
response = (yield sampleTwoApiRequest());
}
if (response.errors) {
return yield put(failureAction(response.errors));
}
yield put(successAction(response.data));
} catch (error) {
yield put(failureAction(error));
}
}
Now to the problem, my test to the saga looks like this:
/path/redux/saga/sampleSaga/sampleSaga.test.js
import { sampleSaga } from './sampleSaga';
import { sampleOneApiRequest, sampleTwoApiRequest } from 'path/api';
import { successAction } from 'path/redux/action';
import { put } from 'redux-saga/effects';
jest.mock('path/api', () => ({
sampleOneApiRequest: async () => { id: 'sample1' },
sampleTwoApiRequest: async () => { id: 'sample2' }
}));
descripe('test sampleSaga', () => {
if('test sampleSaga switch false', () => {
const generator = sampleSaga({ payload: { switch: false } });
const apiResponse = { data: { id: 'sample1' } };
expect(generator.next().value).toEqual(sampleOneApiRequest());
expect(generator.next(apiResponse).value).toEqual(put(successAction(apiResponse)))
});
if('test sampleSaga switch true', () => {
const generator = sampleSaga({ payload: { switch: true } });
const apiResponse = { data: { id: 'sample2' } };
expect(generator.next().value).toEqual(sampleTwoApiRequest());
expect(generator.next(apiResponse).value).toEqual(put(successAction(apiResponse)))
});
});
The problem is, that the second triggert saga, generate a request to the backend, but i aspect the the request to the backend will be mocked. The frist one will mocked perfectly, when i change the order of both tests, always still the second one (in order) will be call to the backend. When i comment out the first test, the second works fine.
I don't know what its wrong.