首页 > 解决方案 > 为什么在使用 mock-fs 时动态导入会在测试之间意外耦合?

问题描述

我正在尝试对使用ES6 动态导入mock-fs的代码进行单元测试。

当我使用动态导入时,测试之间似乎存在意想不到的耦合,即使我restore()在每次测试后都调用。它看起来好像fs.readFile()在测试之间表现得如预期(无耦合),但await import()有耦合(它返回前一个测试的结果)。

我创建了一个重现问题的最小 Jest 测试用例。测试单独通过,但一起运行时不通过。我注意到,如果我更改directory值以使其在每个测试之间有所不同,那么它们会一起通过。

你能帮我理解为什么这不起作用,它是否是一个错误,以及我应该在这里做什么?

import path from 'path';
import { promises as fs } from 'fs';
import mockFs from 'mock-fs';

const fsMockModules = {
  node_modules: mockFs.load(path.resolve(__dirname, '../node_modules')),
};

describe('Reproduce dynamic import coupling between tests', () => {
  afterEach(() => {
    mockFs.restore();
  });
  it('first test', async () => {
    const directory = 'some/path';
    mockFs({
      ...fsMockModules,
      [directory]: {
        'index.js': ``,
      },
    });
    await import(path.resolve(`${directory}/index.js`));
    //not testing anything here, just illustrating the coupling for next test
  });
  it('second tests works in isolation but not together with first test', async () => {
    const directory = 'some/path';
    mockFs({
      ...fsMockModules,
      [directory]: {
        'index.js': `export {default as migrator} from './migrator.js';`,
        'migrator.js':
          'export default (payload) => ({...payload, xyz: 123});',
      },
    });
    const indexFile = await fs.readFile(`${directory}/index.js`, 'utf-8');
    expect(indexFile.includes('export {default as migrator}')).toBe(true);
    const migrations = await import(path.resolve(`${directory}/index.js`));
    expect(typeof migrations.migrator).toBe('function');
  });
});

标签: javascriptnode.jsdynamic-importmock-fs

解决方案


推荐阅读