【发布时间】:2025-12-25 02:55:11
【问题描述】:
我正在使用 fs 模块将 html 字符串导入到我的模块中,如下所示:
const fs = require('fs');
const htmlString = fs.readFileSync("../utils/htmlString.html").toString();
然后,在我的测试文件中,我尝试像这样模拟 fs 模块:
const fs = require('fs');
jest.mock("fs", () => {
return {
readFileSync: jest.fn()
}
})
fs.readFileSync.mockReturnValue("test string");
我可能错误的逻辑告诉我它应该正确地模拟原始字符串导入并将其替换为“测试字符串”字符串。但是,在运行测试时它会抛出:
TypeError:无法读取未定义的属性“toString”
我知道这意味着模拟不成功,因为它应该成功地在字符串实例上调用 .toString()。
我在这里做错了什么?
【问题讨论】:
-
你能显示你的
jest.config.js吗?以及您如何要求要测试的模块?
标签: javascript node.js unit-testing testing jestjs