我正在为我的节点应用程序编写测试。我有一些用于测试我的数据的装置,我遇到了问题,当我在一个方法中改变它们时,它们也会在所有其他测试中被全局改变,这显然与引用有关。现在我想,如果我将我的灯具写入JSON并在每个文件中要求JSON,那么它们将为每个文件提供唯一的引用,现在证明,它们没有。我的问题是:是否有一种简单的方法来处理Node中的灯具,这样每个文件都有一个灯具实例,不会影响其他测试文件。
我目前在每个测试文件中导入我的灯具的方式:
const {fixture1, someOtherFixture } = require('../../../../../fixtures/keywords.json');
require
调用被缓存,因此一旦调用它,连续调用将返回相同的对象。
您可以执行以下操作:
const {fixture1, someOtherFixture } = require('../../../../../fixtures/keywords.json');
const fixtureCopy = JSON.parse(JSON.stringify(fixture1));
const someOtherFixtureCopy = JSON.parse(JSON.stringify(someOtherFixtureCopy));
或使用包裹:
const deepcopy = require('deepcopy');
const {fixture1, someOtherFixture } = require('../../../../../fixtures/keywords.json');
const fixtureCopy = deepcopy(fixture1);
const someOtherFixtureCopy = deepcopy(someOtherFixtureCopy);
或者更改模块以导出每次都会返回新副本的函数。在我看来,这是推荐的方法。
module.exports = {
get() {
return deepcopy(fixture); // fixture being the Object you have
}
}
const fixture = require('./fixture');
const fixture1 = fixture.get();
这不是JSON特有的。在测试中需要重新评估模块并不罕见。可以在Node.js中修改require.cache
,以直接或使用decache
等帮助程序来影响模块的缓存方式。
根据具体情况,
decache('../../../../../fixtures/keywords.json')
在require
测试前,或afterEach
清理。