Skip Main Navigation

A quick trick for Jest asynchronous tests

17 December 2020 · 1 min read

  • Code snippet to clear all promises
  • Jest has several ways to write tests for asynchronous code
  • Sometimes we mess up and don’t write the test correctly

    • Jest by default passes tests even if no assertions happen
    • Tests pass even though the test never runs your assertions
  • There is expect.hasAssertions you can use to make sure a case ran at least one assertion
  • Don’t want to have to put that into every test
  • In Jest config you can add a beforeEach with expect.hasAssertions() and it’ll run for all tests
  • Be prepared, if you’re adding it after the fact, you may have lots of tests to fix! 😄

Keep learning my friends. 🤓

Hi, I'm Ben Ilegbodu. 👋🏾

I'm a Christian, husband, and father of 3, with 15+ years of professional experience developing user interfaces for the Web. I'm a Principal Frontend Engineer at Stitch Fix, frontend development teacher, Google Developer Expert, and Microsoft MVP. I love helping developers level up their frontend skills.

Discuss on Twitter // Edit on Github

Attend upcoming minishops

Minishops by Ben Ilegbodu are fully-remote workshops that last about 3 hours. They’re highly-focused, covering only the concepts you want to learn so that you can level up your skills and get on with the rest of your day.