我试图通过监视来测试我的单元测试中是否已调用了服务。该服务由视图提供程序中的父组件提供给我的组件。
间谍似乎无法正常工作,并调用了服务类中的真实方法。我相信它与我作为视图提供者提供的服务有关,并且我无法获得要监视的服务的正确实例……有人知道我如何获得要监视的类的正确实例吗?我知道我可能会取消该服务,但我希望有一个更好的解决方案。
@Component({
selector: 'child-selector',
templateUrl: 'child.component.html'
})
export class Component implements OnInit {
constructor(
readonly service: TheService
) {}
onSubmit() {
this.service.doThing();
}
}
@Component({
selector: 'container',
template: `
<child-selector
></child-selector>
`,
viewProviders: [The Service]
})
export class ParentComponent {
}
describe('Componet => ', () => {
let fixture;
let componentInstance;
let debugElement: DebugElement;
let service;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
CommonModule,
HttpClientTestingModule,
ReactiveFormsModule
],
providers: [
FormBuilder,
TheService,
],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents().then(() => {
fixture = TestBed.createComponent(Component);
componentInstance = fixture.componentInstance;
debugElement = fixture.debugElement;
// service = TestBed.get(TheService);
service = debugElement.injector.get(TheService);
});
}));
it('should call service to do thing ', () => {
spyOn(service, 'doThing');
componentInstance.onSubmit(formThing);
expect(service.doThing).toHaveBeenCalledTimes(1);
});
});