skip to Main Content
  • node: 20.15.1
  • jest: 29.7.0
  • jest-environment-jsdom: 29.7.0
const response = await fetch(url, { signal: AbortSignal.timeout(5000) });

I want to unit test the above line of javascript using Jest. Specifically the timeout behaviour. But is that actually possible?

No matter what I do, I have to mock the fetch function. I can make it reject or timeout or whatever, but I’m really just testing the functionality of the mock.

I kinda feel like this is where JS hands over to the web API. Therefore I can’t unit test it?

2

Answers


  1. fetch and AbortSignal are browser APIs, and their implementation isn’t something Jest or your Node environment controls. In this case, the timeout behavior is baked into how the Web API works, so you’re limited to mocking to simulate it. Unit testing, by its nature, focuses on your code rather than the behavior of third-party APIs or the environment.

    Login or Signup to reply.
  2. You can not and should not test this in a unit test.

    As you correctly stated, you can only mock the fetch-functionality and test how your code reacts to it.

    A unit test should focus on one function and not the underlying functions the tested function is calling. Your code is not the fetch-function, but whatever function is using the fetch-function.
    Of course it is okay to test a private functions implicitely when testing a public funtion or similar, but you should not test a dependency in a unit test.

    Therefore it is correct to mock the fetch-function and assume it works as intended and has been unit tested itself. Your test should test your code, not a dependency of your code.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search