Skip to content Skip to sidebar Skip to footer

Jest Test Fails For Async Function That Calls Another Async Function

I am trying to test an async function that uses data returned by another async function. Here is the code to explain my problem: StudentInfo.js export async function getData() {

Solution 1:

Here is a working example to get you started:

StudentInfo.js

import * asStudentInfofrom'./StudentInfo';

exportasyncfunctiongetData() {
  thrownewError('should not get here');  // <= getData will be mocked
}

exportasyncfunctionfilterStudents() {
  const studentData = awaitStudentInfo.getData();
  return studentData.filter(v => v.id === '2');
}

StudentInfo.test.js

import * asStudentInfofrom"./StudentInfo"describe("StudentInfo", () => {
  test("student data correctly filtered", async () => {
    const studentData = [
      { name: 'student1', id: '1' },
      { name: 'student2', id: '2' },
      { name: 'student3', id: '3' }
    ];
    jest.spyOn(StudentInfo, "getData").mockResolvedValue(studentData);
    awaitexpect(StudentInfo.filterStudents()).resolves.toEqual([{ name: 'student2', id: '2' }]);  // Success!
  });
});

You can use mockFn.mockResolvedValue to mock the return value as a Promise that resolves to the value you pass to it (although it also works fine if you just use mockFn.mockReturnValue since it is valid to call await on a value, for example const five = await 5; // <= works fine).

The important part is to use .resolves to tell Jest that the expected value is a Promise that you expect to resolve, and then chain the toEqual to assert on the expected resolved value.

Post a Comment for "Jest Test Fails For Async Function That Calls Another Async Function"