开玩笑模拟'fs'模块 [英] Mock 'fs' module in jest

查看:60
本文介绍了开玩笑模拟'fs'模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图像这样模拟fs模块:

I'm trying to mock the fs module like so:

jest.mock('fs');

正如这篇文章中所见-用笑话嘲笑fs函数

And as seen in this post - Mock fs function with jest

我应该能够将模块内部的功能视为jest.fn()并使用-例如fs.existsSync.mockReturnValue(false);.

I should be able to treat the functions inside the module as jest.fn() and use - fs.existsSync.mockReturnValue(false); for instance.

但是这似乎不起作用,打字稿给了我很多错误. 我要做的只是断言几个函数,例如mkdirSync被调用了time或带有一些参数,而我似乎正在遇到此错误-

That however does not seem to work and typescript gives me a bunch of errors. All I want to do is assert a couple of functions like mkdirSync to have been called times or with some parameters and I seem to be running into this error -

'The "path" argument must be one of type string, Buffer, or URL. Received type undefined'

我试图将fs.ts添加到__mocks__文件夹中并在其中进行模拟-但这并不幸运.

I tried to add fs.ts to the __mocks__ folder and mock it there - but that was no luck.

我要测试的文件是一个类,并且导入了fs.我正在beforeEach开玩笑的方法中创建一个新的类实例.

The file I am trying to test is a class and it imports fs. I am creating a new class instance in the beforeEach jest method.

因此,一般来讲,我不太在意创建文件或查看文件是否存在,我希望有一个模拟的返回值或实现,而只需检查调用了fs模块函数的参数是什么.

So generally speaking, I don't really care to create a file or see if it exists, I wish to have a mocked return value or an implementation and just check with what parameters the fs module functions have been called.

推荐答案

运行jest和以任何方式模拟文件系统都会导致冲突,因为jest也在使用fs模块来处理运行.

It appears that running jest and mocking the file system in any way results in a conflict as jest is also using the fs module to handle the run.

我发现可以解决此问题的唯一解决方案:

The only solution i have found to overcome this issue:

export class SomeClass {
    fs: typeof fs;
    constructor() { this.fs = fs }
    ///code
}

在测试中像这样模拟fs方法:

Mock the fs methods like so in a test:

someClass.fs = {
    mkdirSync: jest.fn()
} as any;

断言:

expect(someClass.fs.mkdirSync).toBeCalledWith('parameters');

这篇关于开玩笑模拟'fs'模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆