gpt4 book ai didi

node.js - Mocha 正在复制对象的值,因此无法更新它

转载 作者:太空宇宙 更新时间:2023-11-04 01:05:30 25 4
gpt4 key购买 nike

我正在运行 Mocha UT Framework + supertest + chai。

我运行了以下函数:

function Test1(inputObj) {
return function(done) {
...
require
.post('...')
.expect(302)
.end(function(err, res) {
if (err) return done(err);
inputObj.id = 'someIdFromResponse';
console.log('after update: ', inputObj); // inputObj includes id
done();
}
}

function Test2(inputObj) {
return function(done) {
console.log('Test2.inputObj: ', inputObj); // no id is printed!
done();
}
}

运行以下 Mocha 步骤:

var globalInputObj = { name: 'test' };

describe('test suite 1\n', function() {
it('should add id to input obj', Test1(globalInputObj));
it('only prints the globalInputObj', Test2(globalInputObj));
}
...
// this line runs after the describe function, guaranteed!
console.log('globalInputObj: ', globalInputObj); // no id field in object

globalInputObject 在测试函数运行后不会更新,尽管它是通过引用传递的。

我在这里缺少什么?有什么想法可以解决这个问题吗?

最佳答案

这一行

console.log('globalInputObj: ', globalInputObj); // no id field in object

您在 describe 调用执行任何测试运行之前放置的内容。因此,您没有得到想要的结果也就不足为奇了。在对问题的编辑中,您会显示一系列 it 调用,其中一个 it 调用取决于前一个调用。这不是设置测试的正确方法。使用 Mocha 的正确方法是确保每个测试独立于另一个测试。任何初始化代码都应该位于 beforebeforeEach Hook 中。根据您更新的问题,您可以像这样构建测试:

describe('test suite 1\n', function() {
// Initialize a test object.
var inputObj = { name: 'test' };

// The before hook gets
before(function (done) {
...
require
.post('...')
.expect(302)
.end(function(err, res) {
if (err) return done(err);
inputObj.id = 'someIdFromResponse';
done();
}
});

it('should add id to input obj', function () {
assert.equal(inputObj.id, 'someIdFromResponse');
});

it('only prints the globalInputObj', function () {
console.log('inputObj: ', inputObj);
});
}

我使用上面的 assert.equal 来执行断言。您可以使用任何您喜欢的断言库。

关于node.js - Mocha 正在复制对象的值,因此无法更新它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23477708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com