0
0
Node.jsframework~30 mins

Testing async code in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Testing Async Code in Node.js
📖 Scenario: You are building a small Node.js module that fetches user data asynchronously. You want to write tests to make sure your async function works correctly.
🎯 Goal: Create a simple async function that returns user data after a delay, then write a test using async/await to verify it returns the expected result.
📋 What You'll Learn
Create an async function called fetchUser that returns a user object after a 100ms delay
Create a variable called expectedUser with the exact user data to compare
Write an async test function called testFetchUser that awaits fetchUser and checks the result
Add a final call to testFetchUser to run the test
💡 Why This Matters
🌍 Real World
Testing async functions is common when working with APIs, databases, or any delayed operations in Node.js applications.
💼 Career
Understanding how to test async code is essential for backend developers to ensure their code works reliably and to catch bugs early.
Progress0 / 4 steps
1
Create the async function fetchUser
Create an async function called fetchUser that returns the object { id: 1, name: 'Alice' } after a 100 millisecond delay using setTimeout inside a Promise.
Node.js
Need a hint?

Use return new Promise(resolve => { setTimeout(() => resolve(...), 100) }) inside your async function.

2
Create the expected user data variable
Create a variable called expectedUser and assign it the object { id: 1, name: 'Alice' }.
Node.js
Need a hint?

Use const expectedUser = { id: 1, name: 'Alice' };

3
Write the async test function testFetchUser
Write an async function called testFetchUser that calls fetchUser() with await, stores the result in a variable called user, and then uses if to check if JSON.stringify(user) === JSON.stringify(expectedUser). If true, return 'Test passed', else throw an error with message 'Test failed'.
Node.js
Need a hint?

Use const user = await fetchUser(); and compare with expectedUser using JSON.stringify.

4
Call the test function testFetchUser
Add a call to testFetchUser() and handle the returned promise by adding .then to log 'Test passed' and .catch to log the error message.
Node.js
Need a hint?

Call testFetchUser() and add .then and .catch to handle success and error.