我正在尝试用Jest测试Sagas,但无法让Sagas调用 loginApi 模拟函数,似乎它正在调用实际函数。有人可以帮我吗?
那是我的传奇:
export async function loginApi(user) {
return await api.post('/auth/customers/login', {
email: user.email, //customer1@mi.me
password: user.password, //12345678
});
}
// Saga function that handles the side effect when the loginWatcher is triggered
export function* loginActionEffect(loginAction) {
//console.tron.log('login Action Effect');
try {
const response = yield call(loginApi, loginAction.user);
// console.log('response:' + response);
yield AsyncStorage.setItem('access_token', response.data.access_token);
yield put(LoginActions.setLogin(loginAction.user));
yield put(LoginActions.setError(''));
} catch (e) {
//console.log('problema com o login!');
yield put(LoginActions.setError('Email ou senha incorretos!'));
}
}
那是我的考验:
it('should receive token in case of success', async () => {
const mockToken = {token: 'kaajfalkfjlaniurvayeg'};
const loginApi = jest.fn().mockImplementation(() => Promise.resolve(mockToken));
const dispatched = [];
const result = await runSaga(
{
dispatch: action => dispatched.push(action),
},
loginActionEffect,
);
expect(loginApi).toHaveBeenCalled();
expect(dispatched).toContainEqual(Creators.setLogin());
expect(dispatched).toContainEqual(Creators.setError());
loginApi.mockClear();
});
那是我的测试结果:
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
21 | );
22 |
> 23 | expect(loginApi).toHaveBeenCalled();
| ^
答案 0 :(得分:1)
runSaga
返回一个Task
对象而不是一个Promise
,因此您需要调用toPromise
const result = await runSaga(
{
dispatch: action => dispatched.push(action),
},
loginActionEffect,
).toPromise();
PS。您测试Sagas的方式违反了建议。请阅读此docs。正如我在评论中所写。关于声明式效果的一件很酷的事情是,效果执行依赖于解释器。因此,您无需在测试中实际执行或模拟任何事情。