我有服务
import { HUNT_SERVICE } from '../../home/home.module';
@Injectable()
export class SupportsService {
private listOfScannedSupports: Observable<PortableObjectResult>[] = [];
constructor(@Inject (HUNT_SERVICE) private huntService: IHuntService) {}
使用injectionToken定义和提供如下内容:
export const HUNT_SERVICE = new InjectionToken<IHuntService>('HuntService');
...
providers: [
{
provide: HUNT_SERVICE,
useClass: HuntService
},
SupportsService
]
效果很好。
我试图像这样在Jest中测试SupportsService:
import { HUNT_SERVICE } from '../../home/home.module';
import { SupportsService } from './supports.service';
describe('SupportsService', () => {
let supportsServiceTest: SupportsService;
let huntService: IHuntService;
const mockHuntService = {
startHuntThenReadPortableObject: jest.fn(query => mockPortableObjectReturn),
};
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
providers: [
SupportsService,
{ provide: HUNT_SERVICE, useValue: mockHuntService },
],
}).compileComponents();
}),
);
beforeEach(() => {
supportsServiceTest = TestBed.inject(SupportsService);
huntService = TestBed.inject(HUNT_SERVICE);
});
it('should be created', () => {
expect(supportsServiceTest).toBeTruthy();
});
启动测试时出现此错误:
src/renderer/app/features/supports/services/supports.service.spec.ts (7.707 s)
● SupportsService › should be created
NullInjectorError: R3InjectorError(DynamicTestModule)[SupportsService -> undefined -> undefined]:
NullInjectorError: No provider for undefined!
at NullInjector.Object.<anonymous>.NullInjector.get (../packages/core/src/di/injector_compatibility.ts:246:21)
我不明白我错过了什么!