我有一些困难,试图建立一个数据库的测试目的。应该删除存储在数据库中的数据,为每个测试重新填充数据。我目前正在做以下工作:
db.js
const mongoose = require('mongoose');
// a Mongoose model describing an entity
const Entity = require('entity-model');
// entities.mock is an array containing entity objects.
const mockedEntities= require('./entities.mock');
function setUp() {
Entities.collection.insertMany(mockedEntities);
}
function breakDown() {
mongoose.connection.on('connected', () => {
mongoose.connection.db.dropDatabase();
});
}
module.exports = { setUp, breakDown };然后在我的test.js里
const db = require('./db');
describe('e2e tests to make sure all endpoints return the correct data from the database', () => {
beforeEach(async () => {
await db.breakDown();
db.setUp();
});
it('should check store-test-result (UR-101)', (done) => ...perform test);
it('should check store-nirs-device (UR-102)', (done) => ...perform test);
});在重新正确填充数据库之前,我似乎没有清空数据库。对原因有什么建议吗?
发布于 2019-11-18 08:08:48
最后我做了:
beforeEach(async () => {
await MyEntity.collection.drop();
await MyEntity.collection.insertMany(mockedMyEntity);
});这解决了我的问题。
如果这导致找不到Mongo错误,则需要在删除集合之前显式地在数据库中创建集合。如果集合不存在,则会发生这种情况。您可以通过在前面添加a来做到这一点:
before(async () => {
await MyEntity.createCollection();
});不要在您的模型中设置选项: autoCreate为true,因为根据https://mongoosejs.com/docs/guide.html#autoCreate,这在生产中不应该设置为false。
https://stackoverflow.com/questions/58875857
复制相似问题