需要 JSON 作为深拷贝

Require JSON as deep copy

我现在正在为我的节点应用程序编写测试。 我有用于测试数据的固定装置,我 运行 进入问题,当我在方法中更改其中任何一个时,它们也会针对所有其他测试进行全局更改,这显然必须做与参考。现在我想如果我将我的固定装置写入 JSON 并在每个文件中要求 JSON 那么它们将对每个文件都有唯一的引用,现在证明它们没有。 我的问题是:是否有一种简单的方法来处理 Node 中的固定装置,以便每个文件都有一个不会影响其他测试文件的固定装置实例。

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

const {fixture1, someOtherFixture } = require('../../../../../fixtures/keywords.json');

require 调用被缓存,所以一旦你调用它,连续调用将 return 同一个对象。

您可以执行以下操作:

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

或者更改您的模块以导出一个每次都会 return 新副本的函数。这是我认为推荐的方法。

module.exports = {
   get() {
      return deepcopy(fixture); // fixture being the Object you have 
   }
}

const fixture = require('./fixture');

const fixture1 = fixture.get();

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

这样的助手

视情况而定,

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

在测试中 require 之前,或 afterEach 进行清理。