javascript - 为什么在使用 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');
});
});
解决方案
推荐阅读
- tensorflow - TensorFlow:为什么 RMSE 计算出来的结果类似于 MAE
- scala - Scala 在 udf 中访问或传递数据帧
- ms-access - 当我认为 NoMatch 应该为 False 时访问 VBA NoMatch = True,我哪里出错了?
- microsoft-graph-api - REST V1.0 API 贬值
- html - 防止滚动到填充区域
- sql - 如何在 SQL 中以高性能的方式使用 PARTITION BY 获取最新记录?
- python - 在循环中连接数字和字符串的最干净和 Pythonic 的方法,同时保持零前缀
- c# - 如何将不同的视频流传输到多个客户端
- r - 生成因子列列表
- powershell - 使用“2”参数调用“InvokeSet”的异常:“未知错误(0x80005000)”