注入MdDialogRef的测试组件是调用服务

时间:2017-03-21 15:29:01

标签: angular service jasmine mddialog testbed

我在测试具有MdDialogRef和注入服务的组件时遇到问题。我想测试一下这个组件正在调用注入的服务。问题是我无法使用通常的

检索服务
fixture = TestBed.createComponent(...); 
component = fixture.componentInstance; 
service = fixture.debugElement.injector.get(Service);

因为必须像这样检索带有注入MDDialogRef的组件:

dialog = TestBed.get(MdDialog);
dialogRef = dialog.open(CompanyLogoComponent);
component = dialogRef.componentInstance;

这是MdDialogRef的一种解决方法,它说“没有可用于MdDialogRef的提供程序”,并且在提供需要许多参数时。 (也许有更好的方法如何做到这一点,然后使用夹具?)

因此,没有可用于检索服务的工具...'debugElement.injector ...'

注入服务时,我有另一个范围,因为间谍没有反应:

it('method should call service', inject ([Service], (service: Service) =>  {
expect(service).toBeTruthy();
spyOn(service, 'method').and.callThrough();
component.methodCallingService();
expect(service.method).toHaveBeenCalled();
}));

知道如何将范围绑定到此处的组件或通过组件检索服务(dialogRef.componentInstance)?

1 个答案:

答案 0 :(得分:4)

我如何解决这个问题:

在TestComponent中,注入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。