我在测试具有 MdDialogRef 和注入(inject)服务的组件时遇到问题。我想测试该组件是否正在调用注入(inject)的服务。问题是我无法用通常的方式检索服务
fixture = TestBed.createComponent(...);
component = fixture.componentInstance;
service = fixture.debugElement.injector.get(Service);
因为必须像这样检索具有注入(inject) MDDialogRef 的组件:
dialog = TestBed.get(MdDialog);
dialogRef = dialog.open(CompanyLogoComponent);
component = dialogRef.componentInstance;
这是 MdDialogRef 的一种解决方法,它表示“没有可用于 MdDialogRef 的提供程序”,并且在提供需要许多参数时。 (也许有更好的方法来做到这一点然后使用固定装置?)
因此,没有可用的固定装置来检索服务...'debugElement.injector...'
当注入(inject)服务时,我有另一个作用域,因为 spy 没有反应:
it('method should call service', inject ([Service], (service: Service) => {
expect(service).toBeTruthy();
spyOn(service, 'method').and.callThrough();
component.methodCallingService();
expect(service.method).toHaveBeenCalled();
}));
知道如何将范围绑定(bind)到此处的组件或通过组件(dialogRef.componentInstance)检索服务吗?
最佳答案
我如何解决这个问题:
在TestComponent内部,注入(inject)MdDialog并设置dialogRef:
public dialogRef: MdDialogRef<TestComponent>;
constructor(private dialog: MdDialog, private service: TestService){}
在TestComponent.spec中,您可以像往常一样通过fixture获取TestService
describe('TestComponent', () => {
let component: TestComponent;
let testService;
let fixture;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
MaterialModule,
MdDialogModule],
declarations: [TestComponent],
providers: [TestService]
})
.overrideModule(BrowserDynamicTestingModule, {
set: {
entryComponents: [TestComponent]
}
})
.overrideComponent(TestComponent, {
set: {
providers: [
{provide: TestService, useClass: MockTestService},
]
}
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
companyService = fixture.debugElement.injector.get(TestComponent);
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
要设置entryComponents,您可以覆盖BrowserDynamicTestingModule。
关于angular - 注入(inject) MdDialogRef 的测试组件正在调用服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42931441/