const mock = require('mock-fs'); gives "TypeError: Cannot read properties of undefined (reading 'read')"

350 Views Asked by At

Here is the full error output:

Test suite failed to run

    TypeError: Cannot read properties of undefined (reading 'read')

      2 | const { default: axios } = require('axios');
      3 | const fs = require('fs');
    > 4 | const mockFs = require('mock-fs');

The module mock-fs is definitely installed, and I have deleted node_modules and reinstalled...

I am using VSCode on WSL1.

How do I import mock-fs?

1

There are 1 best solutions below

0
Tony Schirmer On

This is due to running:

jest.mock('fs');

before it runs the mock.

If you do, then the process that mock-fs uses to fetch the readContext no longer works:

This is within readfilecontext.js

exports.getReadFileContextPrototype = function () {
  const fs = require('fs');
  const fsBinding  = process.binding('fs');

  const originalOpen = fsBinding.open;
  let proto;

  fsBinding.open = (_path, _flags, _mode, req) => {
    proto = Object.getPrototypeOf(req.context);
    return originalOpen.apply(fsBinding, [_path, _flags, _mode, req]);
  };;

  fs.readFile('/ignored.txt', (err) => {});

  fsBinding.open = originalOpen;
  return proto;
}

After that's run, the fsBinding.open is never called (due to the fs.readFile being mocked, and the readFileContext always stays undefined.

This is happening to me using jest + typescript + mock-fs on es6 module mode. When I was using commonjs without typescript, it ran with the jest.mock('fs') just fine.