myHotTake

Tag: JavaScript async

  • How to Test Asynchronous JavaScript Code with Jest

    Hey there! If you enjoy this story and find it helpful, feel free to give it a like or share it with someone who might need it.


    I’m working on a group project, and each team member has their own tasks to complete. Now, not everyone works at the same pace—some might get their work done instantly, while others might take a bit longer. That’s exactly how asynchronous code behaves in JavaScript, and testing it with Jest is like ensuring that everyone in the group project is contributing their part effectively.

    Picture this: I’m responsible for gathering everyone’s contributions and putting together our final presentation. First, I check in with Alex, who quickly sends over their completed section. Easy enough! But then there’s Jamie, who’s still working on their part. I can’t just wait around doing nothing, so I decide to multitask—reviewing Alex’s work and preparing the slides with what I have so far.

    To make sure everything is ready in time, I set up a system where I periodically check if Jamie has finished. In Jest, this is like using async and await or promises to test asynchronous functions. I might use done() when I need to signal that the task is complete, just like I would with Jamie when they finally send over their contribution.

    Sometimes, I’ll even set a deadline, saying, “Jamie, I need your part by 3 PM.” In Jest, this is akin to setting timeouts for my tests to ensure they don’t run indefinitely. Once Jamie sends me their work, I quickly integrate it, making sure everything fits together seamlessly.


    JavaScript Code Example

    Let’s say we have a function fetchSection that simulates fetching a team member’s work. This function returns a promise that resolves after a delay, representing the time it takes for each member to complete their task.

    // Mock function representing an asynchronous task
    function fetchSection(member) {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(`${member}'s work is done!`);
        }, Math.random() * 2000);
      });
    }
    
    // Jest test for the asynchronous function
    test('fetchSection completes work for Alex', async () => {
      const result = await fetchSection('Alex');
      expect(result).toBe("Alex's work is done!");
    });
    
    test('fetchSection completes work for Jamie', async () => {
      const result = await fetchSection('Jamie');
      expect(result).toBe("Jamie's work is done!");
    });

    Explanation

    • Promises and async/await: Just like how I wait for Jamie’s part while working on other tasks, async and await help me manage asynchronous operations without blocking the entire process.
    • Mocking Delays: The setTimeout simulates the varying times each team member might take to finish their work.
    • Test Assertions: Using expect ensures that once the promise resolves, I indeed receive the expected output, just like checking if the work fits into the presentation.

    Key Takeaways

    • Asynchronous Testing in Jest: Utilize async functions and await to handle promises gracefully in your tests, ensuring that asynchronous operations are completed before making assertions.
    • Simulating Delays: Use setTimeout to mimic real-world delays in asynchronous operations during testing.
    • Ensuring Correct Output: Always verify that the resolved value of a promise matches the expected outcome with assertions.