简体   繁体   English

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

[英]How to properly mock fs.readFileSync() in Jest?

I am using the fs module to import a html string to my module, like this:我正在使用 fs 模块将 html 字符串导入我的模块,如下所示:

const fs = require('fs');    
const htmlString = fs.readFileSync("../utils/htmlString.html").toString();

Then, in my test file I am trying to mock the fs module like this:然后,在我的测试文件中,我试图像这样模拟 fs 模块:

const fs = require('fs');
jest.mock("fs", () => {
  return {
    readFileSync: jest.fn()
  }
})
fs.readFileSync.mockReturnValue("test string");

My possibly wrong logic tells me that it should properly mock the original string import and replace it with a "test string" string.我可能错误的逻辑告诉我它应该正确地模拟原始字符串导入并将其替换为“测试字符串”字符串。 However, while running the test it throws:但是,在运行测试时它会抛出:

TypeError: Cannot read property 'toString' of undefined TypeError:无法读取未定义的属性“toString”

I understand that this means the mock was unsuccessful, as it should successfully call.toString() on a string instance.我知道这意味着模拟不成功,因为它应该在字符串实例上成功调用.toString()。

What I am doing wrong in here?我在这里做错了什么?

You don't need to provide the module factory argument explicitly for jest.mock('fs') .您不需要为jest.mock('fs')显式提供模块工厂参数。 jest.mock() mocks a module with an auto-mocked version when it is being required. jest.mock()在需要时使用自动模拟版本模拟模块。 This means the fs.readFileSync is a mock method with same with jest.fn() .这意味着fs.readFileSync是一个与jest.fn()相同的模拟方法。

You need to make sure to require the module under test after mocking the return value, since the code in the module scope will be executed instantly when it's be required.您需要确保在 mocking 返回值之后需要被测模块,因为模块 scope 中的代码将在需要时立即执行。

Eg例如

index.js : index.js

const fs = require('fs');
const htmlString = fs.readFileSync('../utils/htmlString.html').toString();
console.log('htmlString: ', htmlString);

index.test.js : index.test.js

const fs = require('fs');

jest.mock('fs');

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

Test result:测试结果:

 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 : jest.config.js

module.exports = {
  testEnvironment: 'node',
};

package versions: package 版本:

"jest": "^26.6.3"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM