我在NodeJS中使用以下模块:
文件:collection_item.js
var items = [];
var exports = module.exports;
exports = module.exports = function() {
};
exports.prototype.addItem = function(item) {
items.push(item);
};
exports.prototype.deleteItem = function(index) {
items.splice(index, 1);
};
我也用此代码进行测试:
var assert = require("assert");
var itemCollection = require('../../item_collection.js');
describe('Item collection', function(){
describe('#addItem', function(){
it('should add object to the collection', function(){
var collection = new itemCollection();
collection.addItem({
test: 'aaa'
});
assert.equal(collection.count(), 1); // Success
});
});
describe('#deleteItem', function(){
it('should delete the given item from the collection', function(){
var collection = new itemCollection();
var item1 = {
test: 'aaa'
};
var item2 = {
test: 'bbb'
};
var item3 = {
test: 'ccc'
};
collection.addItem(item1);
collection.addItem(item2);
collection.addItem(item3);
collection.deleteItem(2);
assert.equal(collection.count(), 2); // Fails, says it has 3 items
});
});
});
我在这里的问题是第二次测试失败。它断言集合中只剩下2个项目,但是说它只有3个项目。
这是因为第一个测试向集合中添加了1个项目。但是在第二次测试中,我做了一个:
var collection = new itemCollection();
集合为什么不是空的?由于某种原因,它仍然具有在第一个测试中添加的项目。我不明白为什么会这样。
有人知道吗?
您items
不是“私人”会员。
试试这个:
var exports = module.exports;
exports = module.exports = function() {
this.items = [];
};
exports.prototype.addItem = function(item) {
this.items.push(item);
};
exports.prototype.deleteItem = function(index) {
this.items.splice(index, 1);
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句