Testing a file system with Jest?

I use mock-fsto try and test the Webpack plugin that I wrote, which modifies a file in my file system.

Here's the test:

test('writes chunks to build/assets.json if no json file present', () => {
   mockFs({
    [buildDir]: {},
  });

  const stats = new Stats({
    assetsByChunkName: {
      main: 'main.somecrazyhash12341213445345.js',
    },
  });
  const compiler = new Compiler(stats);
  const plugin = new ChunksToJsonPlugin(config);

  expect(fs.existsSync(assetFilePath)).toBe(false);

  plugin.apply(compiler);
  compiler.execHandler();

  expect(fs.existsSync(assetFilePath)).toBe(true);
  expect(fs.readFileSync(assetFilePath, 'utf-8')).toEqual(
    JSON.stringify({
      main: 'main.somecrazyhash12341213445345.js',
    })
  );

  mockFs.restore();
});

It works great when I run it on my own, but when I run it as part of a package, other tests (which don't use mock-fs) break.

ss http://d.pr/i/z2ne+

I noticed that it mock-fsis in stacktrace, which makes me think that the file system is also mocking these tests (which I don't want).

mock-fs states that:

mock-fs @4 . , fs, process.binding('fs'). - , fs (, graceful-fs) Node Node fs.

, process.binding, Jest, , , .

? , mock-fs?

+4
2

, (DI), mock-fs memfs:

import memfs from 'memfs';

// ...

test('writes chunks to build/assets.json if no json file present', () => {
  // eslint-disable-next-line new-parens
  const fs = new memfs.Volume;

  fs.mountSync(buildDir, {});

  // same as before

  const plugin = new ChunksToJsonPlugin(config, fs);
  // ------------------------------------------ ^^

  expect(fs.existsSync(assetFilePath)).toBe(false);

  // same as before

  expect(fs.existsSync(assetFilePath)).toBe(true);
  expect(fs.readFileSync(assetFilePath, 'utf-8')).toEqual(
    JSON.stringify({
      main: 'main.somecrazyhash12341213445345.js',
    })
  );
});

, API ChunksToJsonPlugin, fs live:

import fs from 'fs';

// ...

new ChunksToJsonPlugin(config, fs)

, / , , , , NodeJS . , DI , .

- , mock-fs, DI .

+1

, , , , :

1:

const DIR_BASE = path.resolve(__dirname, '__fixtures__/mytestedmodule');

2:

it('should ...', async () => {
  const DIR_ID = md5('should ...');
  const DIR = path.resolve(DIR_BASE, `data${DIR_ID}`);
  await mytestedmodule(DIR);
  expect(...);
});
  • md5 , .
  • data${DIR_ID}:

3: ,

afterAll(async () => {
  const folders =
    (await fs.readdir(DIR_BASE))
      .filter((folder) => folder.match('data'));
  const promises = [];
  for (const folder of folders) {
    promises.push(fs.remove(path.resolve(DIR_BASE, folder)));
  }
  return Promise.all(promises);
});

, Jest runner, . , . , , , , , , .

0

Source: https://habr.com/ru/post/1663570/


All Articles