Mock 'fs' module in jest

你说的曾经没有我的故事 提交于 2021-01-29 04:13:39

问题


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

jest.mock('fs');

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

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

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'

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

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.

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.


回答1:


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
}

Mock the fs methods like so in a test:

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

Assertion:

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


来源:https://stackoverflow.com/questions/58774426/mock-fs-module-in-jest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!