设置数据库以进行e2e测试失败:E11000重复键错误收集

我在尝试建立数据库以进行测试时遇到了一些麻烦。应该删除存储在数据库中的数据,并为每个测试重新填充。我目前正在执行以下操作:

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

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

xu1988 回答:设置数据库以进行e2e测试失败:E11000重复键错误收集

我最终做了:

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

这解决了我的问题。

如果未找到导致Mongo错误的ns,则需要在删除之前在数据库中显式创建集合。如果该集合不存在,则会发生这种情况。您可以通过添加before来实现:

before(async () => {
    await MyEntity.createCollection();
  });

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

本文链接:https://www.f2er.com/3095894.html

大家都在问