Wes*_*put 7 javascript typescript jestjs
我试图开玩笑地编写一个测试,但当我尝试使用时不断收到 UnhandledPromiseRejectionWarningmockRejectedValue
代码如下所示:
it('Should set error message when call fails', async () => {
const context = mockActionsContext();
const user = {
username: 'alice',
password: 'password'
};
const getError = new Error('network error');
(AuthService.login as jest.Mock) = jest.fn().mockRejectedValue(getError);
await actions[ActionTypes.USER_LOGIN](context, user);
// Check is the commits are called
expect((context.commit as any).mock.calls).toEqual([
[MutationTypes.USER_LOGIN],
[MutationTypes.USER_LOGIN_ERROR, 'Oops, something went wrong. Try again later!']
]);
// Login service is called with user login
expect(AuthService.login as jest.Mock).toHaveBeenCalledWith(user);
});
Run Code Online (Sandbox Code Playgroud)
返回AuthService.login一个 axios.post ,我尝试用模拟覆盖它。
actions[ActionTypes.USER_LOGIN](context, user)调用 Authservice.login
测试正在通过,但我不希望有任何未处理的承诺拒绝。有人知道如何修复它吗?
编辑@goodmorningasif 感谢您的回复。我已经看它太久了:)
该操作如下所示:
[ActionTypes.USER_LOGIN]: ({ commit }: Context, payload: User) => {
return new Promise((resolve, reject) => {
commit(MutationTypes.USER_LOGIN);
AuthService.login(payload)
.then((token) => {
commit(MutationTypes.USER_LOGIN_SUCCESS, token);
localStorage.setItem('user-token', token);
client.defaults.headers.common.Authorization = `Bearer ${token}`;
resolve(token);
})
.catch((error) => {
let errorMessage = 'Oops, something went wrong. Try again later!';
if (error?.response?.status === 401) {
errorMessage = 'Unknown username and password combination!';
}
localStorage.removeItem('user-token');
commit(MutationTypes.USER_LOGIN_ERROR, errorMessage);
reject(error);
});
});
},
Run Code Online (Sandbox Code Playgroud)
解决方案
就我而言,该操作正在返回一个女巫会被拒绝的承诺。在测试中,我直接调用该操作,而没有捕获拒绝。
await actions[ActionTypes.USER_LOGIN](context, user).catch(() => null);
Run Code Online (Sandbox Code Playgroud)
这解决了它。
小智 3
我们可以看到操作和减速器代码吗?您的错误可能有错误:)
您正在测试调用登录函数并且该操作返回您设置的错误消息,但您正在假设导致错误的原因。也许不是因为mockRejectedValue/'网络错误'。
我建议在操作有效负载中包含实际的错误消息以及错误消息:一条用于开发人员和调试,一条用于让用户知道下一步该做什么。
我还发现这有助于理解UnhandledPromiseRejectionWarning: https: //thecodebarbarian.com/unhandled-promise-rejections-in-node.js.html
顺便说一句,找出问题的良好本能并不满足于测试通过!
| 归档时间: |
|
| 查看次数: |
9148 次 |
| 最近记录: |