Better Programming

Advice for programmers.

Follow publication

Member-only story

Test and Mock Asynchronous Calls With the Jest Testing Framework

Jennifer Fu
Better Programming
Published in
6 min readApr 13, 2020
Photo by Petr Macháček on Unsplash

Unit testing isolates each part of the program and verifies that the individual parts are correct. Unit test cases are typically automated tests written and run by developers. This enables problems to be discovered early in the development cycle. Jest is a JavaScript testing framework to ensure the correctness of any JavaScript codebase.

Asynchronous calls don’t block or wait for calls to return. After the call is made, program execution continues. When the call returns, a callback function is executed. It’s hard to test asynchronous calls due to the asynchronous nature.

The Pitfall of Asynchronous Calls

The following is a unit test case for an asynchronous call, setTimeout.

Apparently, 1 isn’t 2, but the test passes.

This is the pitfall of asynchronous calls. Line 3 calls setTimeout and returns. The test…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Write a response