jeudi 26 mars 2020

How to connect to MongoDB from Jest test

I wish to test some business logic that writes to mongodb. After the writing is complete. I wish to query the database to assert that the action was done correctly. I am unable to define a model in my test and query this.

jest.config.js

{
  testEnvironment: 'node',
}

Jest Test File

const mongoose = require('mongoose');

  describe('mongoose', () => {

  beforeAll(async () => {
      await mongoose.connect('mongodb://localhost:27017/test_database');
      console.log('connected!');
  });

  afterAll(async () => {
      await mongoose.disconnect();
      console.log('disconnected!');
  });

  it('should find records in the database', async () => {
      const model = mongoose.Schema({
          key: mongoose.Schema.Types.String,
      });
      const Record = mongoose.model('record', model);
//                           ^ ERROR
      const result = await Record.find({});
      expect(result).toBeDefined();
  });
});

Though I get an error when using the model:

TypeError: Cannot read property 'Decimal128' of null

  at Object.<anonymous> (node_modules/mongoose/lib/types/decimal128.js:13:44)
  at Object.<anonymous> (node_modules/mongoose/lib/utils.js:11:17)
  at Object.<anonymous> (node_modules/mongoose/lib/statemachine.js:8:15)
  at Object.<anonymous> (node_modules/mongoose/lib/internal.js:7:22)

Any suggestions on what I need to do?

Aucun commentaire:

Enregistrer un commentaire