我试图构建weatherService测试模块,但发生了错误。WeatherRepo是一个访问数据库并注入weatherService的提供程序。HttpModule也有类似的问题。我没有将HttpModule传递到导入中,而是将HttpService传递到提供中。如果我使用自动模拟或重写,这可以工作,但不像我预期的那样。
这里有一个错误:
Error: Nest can't resolve dependencies of the WeatherRepo (?). Please make sure that the argument WeatherRepository at index [0] is available in the RootTestModule context.
Potential solutions:
- Is RootTestModule a valid NestJS module?
- If WeatherRepository is a provider, is it part of the current RootTestModule?
- If WeatherRepository is exported from a separate @Module, is that module imported within RootTestModule?
@Module({
imports: [ /* the Module containing WeatherRepository */ ]
})
字符串
weather.module.ts
@Module({
imports: [HttpModule, SequelizeModule.forFeature([Weather])],
controllers: [WeatherController],
providers: [WeatherService, WeatherRepo],
exports: [WeatherService],
})
export class WeatherModule {}
型
天气.服务.规格.ts
describe('WeatherService', () => {
beforeEach(async () => {
const weatherServiceModule: TestingModule = await Test.createTestingModule({
providers: [WeatherService, ConfigService, WeatherRepo],
imports: [HttpModule],
})
// .overrideProvider(WeatherRepo)
// .useValue(mockWeatherRepo)
.compile();
weatherService = weatherServiceModule.get<WeatherService>(WeatherService);
weatherRepo = weatherServiceModule.get<WeatherRepo>(WeatherRepo);
httpService = weatherServiceModule.get<HttpService>(HttpService);
});
it('should be defined', async () => {
jest
.spyOn(weatherRepo, 'findOrCreate')
.mockResolvedValue(CreatedWeather(false));
jest.spyOn(weatherRepo, 'update').mockResolvedValue(2);
jest.spyOn(httpService, 'get').mockResolvedValue({ data: CreateWeather() });
});
型
weather.service.ts
@Injectable()
export class WeatherService {
constructor(
private readonly httpService: HttpService,
private readonly config: ConfigService,
private readonly weatherRepository: WeatherRepo,
) {}
}
型
weather.repo.ts
@Injectable()
export class WeatherRepo {
constructor(@InjectModel(Weather) private weatherModel: typeof Weather) {}
}
型
我想提供所有必需的provides/imports/controllers并获得结果(准备工作TestingModule)。既不覆盖也不自动模拟,因为我想用spyOn控制服务的行为。我不知道如何解决这个问题。有人能帮忙吗?
1条答案
按热度按时间hl0ma9xz1#
您需要为
WeatherRepository
提供程序(即通过@InjectModel(Weather)
注入的提供程序)提供一个mock,或者需要使用SequelizeModule.forRoot()
连接到数据库,然后像在WeatherModule
中使用SequelizeModule.forFeature([Weather])
一样提供实际的提供程序