需要JSON作为深层副本

问题描述 投票:1回答:2

我正在为我的节点应用程序编写测试。我有一些用于测试我的数据的装置,我遇到了问题,当我在一个方法中改变它们时,它们也会在所有其他测试中被全局改变,这显然与引用有关。现在我想,如果我将我的灯具写入JSON并在每个文件中要求JSON,那么它们将为每个文件提供唯一的引用,现在证明,它们没有。我的问题是:是否有一种简单的方法来处理Node中的灯具,这样每个文件都有一个灯具实例,不会影响其他测试文件。

我目前在每个测试文件中导入我的灯具的方式:

const {fixture1, someOtherFixture } = require('../../../../../fixtures/keywords.json');
node.js json testing fixtures
2个回答
1
投票

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();

0
投票

这不是JSON特有的。在测试中需要重新评估模块并不罕见。可以在Node.js中修改require.cache,以直接或使用decache等帮助程序来影响模块的缓存方式。

根据具体情况,

decache('../../../../../fixtures/keywords.json')

require测试前,或afterEach清理。

© www.soinside.com 2019 - 2024. All rights reserved.