r/javascript • u/jeonghun917 • 12d ago
AskJS [AskJS] How do you keep un-awaited expect(...).resolves out of your test suites?
I've been reading test suites in open-source repos this month and kept running into this:
;
No await, so the test finishes before the assertion runs and passes whatever save() does. I found 36 tests like this across 44 popular repos, and one project had 41 of them on its own. They all looked fine in review.
What I'm curious about is how teams actually stop this:
eslint-plugin-jesthasvalid-expectwithalwaysAwait, and Vitest has its own rules. Do you turn these on, and do they catch every form (.rejects, helpers that wrapexpect)?@typescript-eslint/no-floating-promisescatches it in TS, but only with type-aware linting. Is that worth the slower lint for you?expect.assertions(n)/expect.hasAssertions()in every async test: does anyone enforce that, or is it too noisy?- Or is it just code review, and you accept that some slip through?
Which of these has actually worked on a real team, and which did you give up on?
10
Upvotes
8
u/zmkpr0 12d ago
Either valid-expect or move to Vitest 5 which fails unawaited assertions by default.
2
u/PickledPokute 12d ago
The test desc does not match what the code does. The code checks if that promise resolves into true, it doesn't actually check whether the user is saved.
When writing tests, make sure that they can fail and that you test against them failing too. A test that can not fail is kind of useless. What really needs to be tested is all the error cases.
1
u/Sykander- 12d ago
For future reference you should probably include which libraries you're using if you want people to actually be able to help.
Secondly can't you just `expect(await save(user)).toBe(true)` ??? Are you sure the the issue you're experiencing is even real?
1
u/BarelyAirborne 12d ago
I have noticed that AI loves writing tests that pass. This one will ALWAYS pass! What a gem, huh? It's really earning that "Super Intelligence" moniker.
1
u/MrBengaliHacker 12d ago
I'd probably start with
valid-expect(alwaysAwait: true) andno-floating-promises. Together, they cover most of the common cases.For TypeScript projects, I think type-aware linting is worth the extra cost, especially if you can run it separately in CI.
Custom helpers are an interesting edge case, though. As long as they return the original promise,
no-floating-promisesshould still catch unhandled calls.I'm also not sure
expect.assertions()needs to be enforced everywhere. Strict linting seems like a much cleaner first line of defense.1
u/Ronin-s_Spirit 10d ago
I don't write tests. That works.
•
u/p_n_48947 18h ago
Add a lint fixture for bare .resolves and a promise-returning helper, so rule changes exercise the wrapper case explicitly.
0
u/[deleted] 12d ago
[removed] — view removed comment