Nest 无法解析 JokeEntityRepository (?) 的依赖关系

时间:2021-06-16 23:03:10

标签: jestjs nestjs ts-jest

我正在学习 NestJS,并且正在尝试测试一个将存储库与 TypeORM 结合在一起的服务。它编译得很好,没有错误,但是当我运行测试时,它抛出一个错误。

我知道这是一个测试依赖问题,但我无法弄清楚。我正在尝试此测试:

describe('JokesService', () => {
  let service: JokesService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [],
      imports: [
        TypeOrmModule.forFeature([JokeEntity])
      ],
    }).compile();

    service = module.get<JokesService>(JokesService);
  });

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

模块:

@Module({
  providers: [JokesService],
  imports: [
    TypeOrmModule.forFeature([JokeEntity])
  ],
  controllers: [JokesController],
})
export class JokesModule {}

服务:

@Injectable()
export class JokesService {
  constructor(
    @InjectRepository(JokeEntity)
    private readonly jokeRepository: MongoRepository<JokeEntity>
  ) {}
}

主要模块:

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mongodb',
      url: dbUri,
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      ssl: true,
      useUnifiedTopology: true,
      useNewUrlParser: true,
    }),
    JokesModule
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

和错误:

 Nest cant resolve dependencies of the JokeEntityRepository (?). 
Please make sure that the argument Connection at index [0] is available in the TypeOrmModule context.

    Potential solutions:
    - If Connection is a provider, is it part of the current TypeOrmModule?
    - If Connection is exported from a separate @Module, is that module imported within TypeOrmModule?
      @Module({
        imports: [ /* the Module containing Connection */ ]
      })

有人能告诉我我在测试依赖项中缺少什么吗?谢谢。

1 个答案:

答案 0 :(得分:0)

尝试将您的 JokesModule 导入您的 app.module

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mongodb',
      url: dbUri,
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      ssl: true,
      useUnifiedTopology: true,
      useNewUrlParser: true,
    }),
    JokesModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}