Testing JavaScript Code with Timeouts and Promises

Spencer Feng
2 min readJul 1, 2023

--

Using timeouts and promises in JavaScript code is a common practice. However, handling them correctly in tests can sometimes be challenging. In this article, we will explore a contrived example to illustrate the proper way of writing tests for code that includes timeouts and promises.

In this example, we will create a Jest test for the handleFetchedMessage function. The handleFetchedMessage function exhibits the following behaviors:

  • It receives a callback as a parameter.
  • It invokes the…

--

--