-
Notifications
You must be signed in to change notification settings - Fork 242
Description
Problem
It is common to write assertions for rejected promises using .rejects. However, sometimes developers write it in a more verbose and unnecessary way like this:
await expect(async () => {
await somePromise();
}).rejects.toThrow('Error');This can be simplified to:
await expect(somePromise()).rejects.toThrow('Error');The async function wrapper adds no value and makes the test harder to read, especially when the only purpose of the function is to wrap a single await call.
Proposal
I'd like to propose a lint rule that detects and warns on unnecessary async function wrappers passed to expect(...).rejects or expect(...).resolves.
There are two possible implementation paths:
Option 1: Extend prefer-expect-resolves
This rule already encourages usage of .resolves / .rejects over try/catch or other patterns.
It may be natural to include this redundant async wrapper pattern as part of that rule’s responsibility.
Option 2: Introduce a new rule
Create a new rule such as no-unnecessary-async-wrapper-in-expect that focuses specifically on this anti-pattern.
It would help keep test code concise and idiomatic.
Example Code
Invalid:
await expect(async () => {
await doSomethingAsync();
}).rejects.toThrow();Valid:
await expect(doSomethingAsync()).rejects.toThrow();Discussion
I'm unsure whether this case is better suited as an extension of prefer-expect-resolves, or whether it's better introduced as a standalone rule. I’d love to hear your thoughts on that — or if there's another preferable approach, I'd really appreciate your guidance.
Thanks for your time!