我正在學習如何編寫一個針對供應商的REST API的NodeJS模塊。模塊本身的關鍵代碼是編寫的,但現在我正試圖學習如何正確地測試它。目前我正在使用MochaJS和ChaiJS作爲測試框架。在一次測試中,我創建了一個返回隨機ID的用戶,我需要保存這個ID。然後,我想使用所述ID值並測試用戶刪除。如何將一個MochaJS測試的值傳遞給另一個?
下面是當前的代碼不起作用:
var names = require('./names.json');
var ids = [];
describe('users', function() {
describe('addUser', function(){
it('should create ' + names[0].firstname, function (done){
this.slow(3000); this.timeout(10000);
api.addUser(names[0],function(x){
x.should.have.property('id').with.length.of.at.least(2);
ids.push(x.id);
done();
});
});
it('should create ' + names[1].firstname, function (done){
this.slow(3000); this.timeout(10000);
api.addUser(names[1],function(x){
x.should.have.property('activated').and.equal(true);
ids.push(x.id);
done();
});
});
});
describe('deleteUser', function(){
for(var a=0;a<ids.length;a++){
it('should delete ' + ids[a], function (done){
api.deleteUser(ids[a],function(x){
x.should.have.property('id').and.equal(ids[a]);
done();
});
});
}
});
});
即使ids
的作用範圍遠遠超出了測試,數值不會被保存。現在我已經閱讀了關於堆棧溢出的其他評論,其中響應者基本上說「不要重用值...某些事情瀑布故障」。我理解但對我來說,這是預期功能(TM)。如果由於任何原因(我的代碼或供應商API)出現故障,並且我無法創建用戶,那麼顯然我將無法刪除用戶。
我想把所有這些放到Travis CI中,所以我不能指望一個特定的用戶將永遠在那裏刪除,除非我的測試框架創建的是。我在供應商系統上的用戶數量有限,所以我需要清理我的測試。還有其他用例(如修改現有用戶),我想測試。
在beforeEach中添加用戶或者在調用delete之前有什麼問題? –
對於其他尋找一個更容易閱讀的例子:[shakataganai/testing-mocha/test.js](https://github.com/ShakataGaNai/testing-mocha/blob/master/test.js) – Jon