Jest异步测试报错:Avoid calling `expect` conditionally 解决方案咨询
Great question! I've run into this exact ESLint rule quirk with Jest's async/await tests before. Even though you've added expect.assertions(1) to guarantee the expect runs, the ESLint rule relies on static analysis and doesn't connect the dots between that assertion and the expect inside the catch block. Here are two clean solutions that don't require disabling the rule:
Solution 1: Use Jest's rejects matcher (recommended)
Jest has built-in support for testing rejected promises directly with the rejects matcher, which eliminates the need for try/catch entirely. This is more concise and avoids the conditional expect issue:
it("Should reject with message, User already exists with same email", async () => { expect.assertions(1); await expect(signupService(userSignupData)).rejects.toContain("User already exists"); });
The rejects matcher waits for the promise to reject, and Jest handles the assertion correctly. The expect.assertions(1) is still useful here to ensure the promise actually rejects (prevents false positives if the promise resolves unexpectedly).
Solution 2: Capture the error outside the catch block
If you prefer to keep the try/catch structure (maybe for more complex error handling), you can capture the error in a variable and assert on it outside the catch block. This moves the expect out of the conditional code block, satisfying ESLint:
it("Should reject with message, User already exists with same email", async () => { expect.assertions(1); let caughtError; try { await signupService(userSignupData); } catch (e) { caughtError = e; } expect(caughtError).toContain("User already exists"); });
This works because the expect is now in the top-level scope of the test, not inside a conditional catch block. The expect.assertions(1) still ensures that the expect runs—if the promise doesn't reject, caughtError will be undefined, and the test will fail as expected.
Why your original code triggers the error
The jest/no-conditional-expect rule is a static analysis tool—it can't dynamically verify that your expect.assertions(1) guarantees the catch block will execute. From its perspective, the expect inside the catch is only run if the promise rejects, making it a conditional call. The solutions above either remove the conditional structure or move the expect out of it entirely.
内容的提问来源于stack exchange,提问作者Bharati

