Search code examples
mongodbnestjsin-memory-database

mongo-inmemory-server in Nestjs throws MongoNotConnectedError


consider this test file

describe('UserRepository', () => {
  let userRepository: UserRepository;
  let module: TestingModule;

  beforeAll(async () => {
    module = await Test.createTestingModule({
      imports: [
        rootMongooseTestModule(),
        MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]),
      ],
      providers: [UserRepository],
    }).compile();

    userRepository = module.get<UserRepository>(UserRepository);
  });

  it('should be defined', () => {
    expect(userRepository).toBeDefined();
  });

  it('can be created correctly', async () => {
    expect(
      async () =>
        await userRepository.create({
          firstName: 'Merlin',
          phone: '734214353',
          email: '[email protected]',
        }),
    ).not.toThrow();
  });

and also this is the in memory config :

export const rootMongooseTestModule = (options: MongooseModuleOptions = {}) =>
  MongooseModule.forRootAsync({
    useFactory: async () => {
      mongod = await MongoMemoryServer.create();
      const mongoUri = mongod.getUri();
      console.log(mongoUri);             //==========> logs mongodb://127.0.0.1:37345/
      return {
        uri: mongoUri,
        ...options,
      };
    },
  });

export const closeInMongodConnection = async () => {
  await mongoose.disconnect();
  if (mongod) await mongod.stop();
};
the `should be defined` test is passed correctly, but the second test throws this
`Test suite failed to run`
`MongoNotConnectedError: MongoClient must be connected to perform this operation`

so as commented in code, the mongo uri is genereted correctly, how to handle the connection?


Solution

  • Ah, putting await before rootMongooseTestModule() fixed it.