2

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.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
moodseller
  • 212
  • 2
  • 14

1 Answers1

0

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');
moodseller
  • 212
  • 2
  • 14