摩卡正在复制对象的值,因此无法更新它

我正在运行摩卡UT框架+ supertest + chai。

我有我运行以下function:

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

运行以下摩卡步骤:

 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 

testing函数运行后globalInputObject不会更新,尽pipe它是通过引用传递的。

我在这里错过了什么? 和任何想法来解决这个问题?

这条线

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

在执行任何testing之前执行您的describe调用之后,您已经放置了它们。 所以你没有得到你想要的结果也就不足为奇了。 在对你的问题进行编辑时,你会看到it调用的序列取决于前一个。 这不是设置testing的正确方法。 使用摩卡的正确方法是确保每个testing独立于另一个testing。 任何初始化代码应该在beforebeforeEach挂钩。 根据你更新的问题,你可以像这样构build你的testing:

 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来执行断言。 你可以使用任何你喜欢的断言库。