Nestjs 中的 mongo-inmemory-server 抛出 MongoNotConnectedError

问题描述 投票:0回答:2

考虑这个测试文件

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

这也是内存中的配置:

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();
};
“应该定义”测试已正确通过, 但第二个测试抛出了这个
`测试套件运行失败`
`MongoNotConnectedError:必须连接 MongoClient 才能执行此操作`

正如代码中注释的那样,mongo uri 已正确生成,如何处理连接?

mongodb nestjs in-memory-database
2个回答
0
投票

啊,把

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


0
投票

好吧,这很奇怪,我仍然不明白为什么会发生这种情况,所以我使用了我在应用程序中使用的常用database.module,在测试中它起作用了。也许这是未来的游客应该尝试的事情。

(这应该是内部评论,但我没有足够的声誉来发表评论,所以将其保留为答案)。

© www.soinside.com 2019 - 2024. All rights reserved.