Bha*_*ati 3 jestjs ts-jest jest-mock-axios react-typescript
我正在尝试在响应被拒绝时测试具有负面情况的异步代码。
根据文档,我们可以在尝试实现模拟拒绝时使用 try、catch 和 async wait https://jestjs.io/docs/tutorial-async
// Or using async/await.
it('tests error with async/await', async () => {
expect.assertions(1);
try {
await user.getUserName(1);
} catch (e) {
expect(e).toEqual({
error: 'User with 1 not found.',
});
}
});
Run Code Online (Sandbox Code Playgroud)
我尝试通过实现模拟拒绝值来执行相同的操作。但是,我收到以下错误:Avoid calling 'expect' conditionally。我还添加了expect.assertions(),但错误仍然存在。我知道可以启用 eslintjest/no-conditional-expect,但这是一个我不想遵循的坏习惯。
it("Should reject with with message, User already exists with same email", async () => {
expect.assertions(1);
try {
await signupService(userSignupData);
} catch (e) {
expect(e).toContain("User already exists");
}
});
Run Code Online (Sandbox Code Playgroud)
任何帮助表示赞赏。谢谢!
PS我看到了类似的问题,但没有解决。
您遇到了来自图书馆的警告eslint-plugin-jest。根据该库的文档,看起来no-conditional-expect您会想要使用一个finally块,也许是这样的:
it(
"Should reject with with message, User already exists with same email",
async () => {
let err;
try {
await signupService(userSignupData);
} catch (e) {
err = e;
} finally {
expect(err).toContain("User already exists");
}
}
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7115 次 |
| 最近记录: |