首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Jest中正确地模拟fs.readFileSync()?

如何在Jest中正确地模拟fs.readFileSync()?
EN

Stack Overflow用户
提问于 2022-01-18 18:33:22
回答 1查看 1.6K关注 0票数 0

我使用fs模块将html字符串导入到我的模块中,如下所示:

代码语言:javascript
运行
复制
const fs = require('fs');    
const htmlString = fs.readFileSync("../utils/htmlString.html").toString();

然后,在我的测试文件中,我试图像这样模拟fs模块:

代码语言:javascript
运行
复制
const fs = require('fs');
jest.mock("fs", () => {
  return {
    readFileSync: jest.fn()
  }
})
fs.readFileSync.mockReturnValue("test string");

我可能错误的逻辑告诉我,它应该正确地模拟原始字符串导入,并将其替换为“测试字符串”字符串。但是,在运行测试时,它会抛出:

TypeError:无法读取未定义的属性“toString”

我理解这意味着模拟是不成功的,因为它应该成功地调用字符串实例上的.toString()。

我在这里做错了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-19 02:53:18

您不需要显式地为jest.mock('fs')提供模块工厂参数。当需要时,jest.mock()用自动模拟版本来模拟模块.这意味着fs.readFileSync是一个与jest.fn()相同的模拟方法。

您需要确保在模拟返回值之后,需要测试的模块,因为模块作用域中的代码将在需要时立即执行。

例如。

index.js

代码语言:javascript
运行
复制
const fs = require('fs');
const htmlString = fs.readFileSync('../utils/htmlString.html').toString();
console.log('htmlString: ', htmlString);

index.test.js

代码语言:javascript
运行
复制
const fs = require('fs');

jest.mock('fs');

describe('70760704', () => {
  test('should pass', () => {
    expect(jest.isMockFunction(fs.readFileSync)).toBeTruthy();
    fs.readFileSync.mockReturnValue('test string');
    require('./');
  });
});

测试结果:

代码语言:javascript
运行
复制
 PASS  stackoverflow/70760704/index.test.js (7.242 s)
  70760704
    ✓ should pass (14 ms)

  console.log
    htmlString:  test string

      at Object.<anonymous> (stackoverflow/70760704/index.js:3:9)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        7.279 s, estimated 8 s

jest.config.js

代码语言:javascript
运行
复制
module.exports = {
  testEnvironment: 'node',
};

包版本:

代码语言:javascript
运行
复制
"jest": "^26.6.3"
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70760704

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档