I'm starting to write e2e tests for my NestJS API, and I would like to use a test database. I imported the MongooseModule in the test module, and it's correctly using the expected test database.
Then, I'd like to clear the collection and re-insert fixtures before my tests. In order to do that, I'd like to use the Mongoose instance used by NestJS. But I didn't succeed, and finally created a second connection (in the beforeAll hook)
I didn't find any solutions yet to avoid this.
Here is the code :
describe('Color', () => {
let app: INestApplication
let db: Connection
beforeAll(async () => {
db = await mongoose.createConnection(process.env.MONGO_TEST_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
})
db.model('Color', ColorSchema)
})
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [
MongooseModule.forRoot(process.env.MONGO_TEST_URL, {
useCreateIndex: true,
useFindAndModify: false
}),
AppModule
]
}).compile()
await db.model('Color').deleteMany({})
await db.model('Color').insertMany(ColorFixtures)
app = moduleFixture.createNestApplication()
await app.init()
})
afterAll(async () => {
await db.close()
await app.close()
})
it('/ (GET)', () => {
return request(app.getHttpServer())
.post('/graphql')
.send({
operationName: 'findAll',
query: 'query findAll { colors { id name } }',
variables: {}
})
.expect(200)
.expect({})
})
})
Any idea?