[英]Mocking the filesystem in Jest tests
我正在为图形模块编写一些测试,并且作为这些测试的一部分,我需要一种模拟fs
模块的方法,该方法应允许我断言数据已被写入假文件系统以及允许我的伪造文件系统提供伪造数据,以测试从文件系统读取的内容。
我知道jest支持“手动模拟”,您可以在其中创建一个静态模拟对象作为代码旁边的文件。 就我个人而言,我希望尽可能避免这种情况,而是使用jest.fn
和/或jest.doMock
在测试文件中定义我的模拟内联。
查看文档 ,我觉得这应该可行,并且我认为我的fs.createWriteStream
是用1个参数调用的,大约占75%。 我只是似乎无法弄清楚如何断言数据已写入我的模拟fs
。
我也知道npm上有各种mock-fs
或类似的模块。 如果可能的话,我宁愿避免使用这些方法,而是使用jest提供的工具完全解决此问题。
到目前为止,这是我的测试代码:
const fs = require('fs');
const pureimage = require('pureimage');
jest.mock('fs', () => ({
createWriteStream: jest.fn((file_name) => {
return file_name;
})
}));
describe('PNG image', () => {
it('can be encoded to a stream', () => {
const PImage = pureimage.make(200, 200);
const context = PImage.getContext('2d');
context.fillStyle = 'rgba(255,0,0, 0.5)';
context.fillRect(0, 0, 100, 100);
expect(pureimage.encodePNGToStream(PImage, fs.createWriteStream('myimage.png'))).resolves;
});
});
完整的项目可以在这里找到: http : //github.com/robertmain/node-pureimage
我最终通过了一个直通流,并对此做出了断言
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.