我正在尝试测试一个使用另一个异步函数返回的数据的异步函数。这是解释我的问题的代码:
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()
函数编写一个测试吗?我已经被这个问题困扰太久了。
最佳答案
这是一个可以帮助您入门的示例:
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
断言预期解析值。
关于javascript - 对于调用另一个异步函数的异步函数, Jest 测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56736193/