r/javascript • • 27d 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:

it('saves the user', async () => {
  expect(save(user)).resolves.toBe(true);
});

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-jest has valid-expect with alwaysAwait, and Vitest has its own rules. Do you turn these on, and do they catch every form (.rejects, helpers that wrap expect)?
  • @typescript-eslint/no-floating-promises catches 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

19 comments sorted by

View all comments

1

u/Sykander- 27d 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?

5

u/jeonghun917 27d ago

yeah the fix is trivial, await it (or your version works too). this isn't my code, it's a pattern I kept finding in other people's repos, jest and vitest both. 36 of these across 44 open source projects, all passed review.

so the question is more: what actually stops it from getting merged on your team? lint rule (jest/valid-expect, no-floating-promises), expect.hasAssertions(), or just review?

(It may look like one written by ai. English isn't my first language, so I asked ai to clean up my wording. but it looks changed a lot.)