端到端测试设置数据库失败:E11000 重复键错误收集

Setting up database for e2e testing fails: E11000 duplicate key error collection

我在尝试设置用于测试目的的数据库时遇到了一些问题。存储在数据库中的数据应该被删除并为每个测试重新填充。我目前正在做以下事情:

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

看来我没有在正确重新填充数据库之前清空数据库。关于可能的原因有什么建议吗?

我最后做了:

beforeEach(async () => {
    await MyEntity.collection.drop();
    await MyEntity.collection.insertMany(mockedMyEntity);
  });

这解决了我的问题。

如果这导致 Mongo 未找到错误,您需要在删除集合之前在数据库中明确创建集合。如果集合不存在,就会发生这种情况。您可以通过添加一个 before:

来做到这一点
before(async () => {
    await MyEntity.createCollection();
  });

不要在您的模型中将选项:autoCreate 设置为 true,因为根据 https://mongoosejs.com/docs/guide.html#autoCreate

不应在生产中将其设置为 false