我想在 Jest 中测试模拟函数的返回值。
在下面的代码中我想模拟 fs 模块的 mkdirSync 函数
const fs = require("fs");
describe("Testing mock fs.mkdirSync", () => {
fs.mkdirSync = jest.fn().mockReturnValue(5);
fs.mkdirSync("./apple");
it("fs.mkdirSync must have been called", () => {
expect(fs.mkdirSync).toHaveBeenCalled();
});
//This test fails with TypeError: Cannot read property '0' of undefined
it("fs.mkdirSync last return value must be 5", () => {
expect(fs.mkdirSync.mock.results[0].value).toBe(5);
});
});
第二个测试因 TypeError 失败:无法读取未定义的属性“0”
最佳答案
为什么要测试 Jest 模拟函数的返回值?此时您正在测试jest
。
您可以将 fs.mkdirSync
分配给一个变量并测试该值,因为这是返回值:
const result = fs.mkdirSync("./apple");
it("fs.mkdirSync last return value must be 5", () => {
expect(result).toBe(5);
});
关于reactjs - 如何在 Jest 中测试模拟函数的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51444891/