mongo-inmemory-server 在 Nestjs 中抛出 MongoNotConnectedError

mongo-inmemory-server in Nestjs throws MongoNotConnectedError

考虑这个测试文件

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: 'merlin@gmail.com',
        }),
    ).not.toThrow();
  });

这也是内存配置:

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();
};
`should be defined` 测试正确通过, 但是第二个测试抛出这个
`测试套件未能 运行`
`MongoNotConnectedError:必须连接 MongoClient 才能执行此操作`

如代码中所述,mongo uri 已正确生成,如何处理连接?

啊,把 await 放在 rootMongooseTestModule() 之前就解决了。