我有 Nest.js 应用程序,其中某些提供程序被注入到另一个提供程序中:
export class AppService {
public constructor(private readonly appInnerService: AppInnerService) {}
}
AppService 有一个publish
调用 appInnerService方法的send
方法。我为 AppService 创建了单元测试,我想在其中模拟 AppInnerService 提供程序:
describe('App service', () => {
let appService: AppService;
const appInnerService = {
send: jest.fn(),
};
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
providers: [AppService, AppInnerService],
})
.overrideProvider(AppInnerService)
.useValue(appInnerService)
.compile();
appService = moduleRef.get<AppService>(AppService);
});
it('should work', () => {
appService.publish({});
expect(appInnerService.send).toHaveBeenCalled();
});
}
上面的代码不起作用,AppInnerService 没有注入到 AppService 中,而是将 undefined 传递给构造函数。为什么上面的测试不起作用,我该如何修复它(无需手动创建带有模拟服务的 AppService 类,我想使用由 @nestjs/testing 包创建的测试模块)?