2016-07-04 24 views
0

我在NodeJS應用程序中使用Mongoose ORM。在集成測試方面,我編寫了一個刪除所有集合afterEach測試的函數。刪除集合後在Mongoose上恢復索引

但現在有一個問題,在收集被刪除後,唯一約束索引不會恢復。

該測試在隔離運行時起作用,因爲在測試運行之前該集合未被刪除。

it('should fail to save when identifier exists', function(done){ 
    newItem.identifier = existingItem.identifier; 
    newItem.save(function (err, result) { 
    should.exist(err); 
    done(null); 
    }); 
}); 

但是,當它的整個測試套件內運行,每次測試之間的集合使用這個輔助方法刪除:

function deleteCollection(collection, done){ 
    var collections = _.keys(mongoose.connection.collections); 
    async.forEach(collections, function (collectionName, next) { 
    var collection = mongoose.connection.collections[collectionName]; 
    collection.drop(function (err) { 
     if (err && err.message != 'ns not found') return next(err); 
     next(null); 
    }) 
}, function(err, result){ 
    done(err, result); 
    }); 
} 

我直接檢查數據庫和收集對標識唯一索引是在運行之間刪除集合後丟失。

有沒有辦法重新運行Mongoose模式,以便在每次測試之間重新創建索引?

回答

0

可以在beforeEach呼籲每個模型ensureIndexes,例如:

beforeEach(function(done) { 
    var modelNames = _.keys(mongoose.models); 
    async.forEach(modelNames, function (modelName, next) { 
    mongoose.models[modelName].ensureIndexes(next); 
    }, done); 
}); 
+0

運作良好,感謝羅伯特。 –