对于调用另一个异步函数的异步函数,Jest测试失败

时间:2019-06-24 12:06:26

标签: javascript unit-testing jestjs enzyme

我正在尝试测试使用另一个异步函数返回的数据的异步函数。这是解释我的问题的代码:

StudentInfo.js

export async function getData() {
  //studentData imported from another file
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(studentData);
    }, 5000);
  });
}

export async function filterStudents() {
  const studentData = await StudentInfo.getData();

  //computations

  return filteredData; //object
}

StudentInfo.test.js

import * as studentInfo from "src/StudentInfo.js"

describe("StudentInfo" , () => {
   test("student data correctly filtered", async () => {
      const studentData = [
         {
            name: Sarah Marshall,
            id: srhmar451
         },
         {...}
      ];
      expectedData = { [...], [...]};
      const spy = jest.spyOn(studentInfo, "getData");
      spy.mockReturnValue(studentData);
      await expect(studentInfo.filterStudents()).toEqual(expectedData);
   });
});

我的测试失败,因为期望的返回值为Promise {}。有人可以帮我为我的filterStudents()函数编写测试吗?我被这个问题困扰了太久了。

1 个答案:

答案 0 :(得分:0)

这是一个让您入门的有效示例:

StudentInfo.js

import * as StudentInfo from './StudentInfo';

export async function getData() {
  throw new Error('should not get here');  // <= getData will be mocked
}

export async function filterStudents() {
  const studentData = await StudentInfo.getData();
  return studentData.filter(v => v.id === '2');
}

StudentInfo.test.js

import * as StudentInfo from "./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);
    await expect(StudentInfo.filterStudents()).resolves.toEqual([{ name: 'student2', id: '2' }]);  // Success!
  });
});

您可以使用mockFn.mockResolvedValue模拟返回值,将其作为Promise解析为您传递给它的值(尽管如果仅使用mockFn.mockReturnValue也可以正常工作,因为它可以可以有效地调用await,例如const five = await 5; // <= works fine)。

重要的部分是使用.resolves告诉Jest期望值是您希望解析的Promise,然后链接toEqual以对其进行断言预期的解决价值。