问题
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() {
//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);
});
});
My test fails because the expected return value is Promise {}
. Could someone help me write a test for my filterStudents()
function? I have been stuck at this for too long.
回答1:
Here is a working example to get you started:
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!
});
});
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.
来源:https://stackoverflow.com/questions/56736193/jest-test-fails-for-async-function-that-calls-another-async-function