2

I'm having a problem with testing a component having MdDialogRef and a service injected. I'd like to test that this component is calling the injected service. The problem is that I can't retrieve the service with the usual

fixture = TestBed.createComponent(...); 
component = fixture.componentInstance; 
service = fixture.debugElement.injector.get(Service);

because the component with an injected MDDialogRef has to be retrieved like this:

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

This is a workaround for MdDialogRef, which says 'no provider available for MdDialogRef', and when providing needing many parameters. (Maybe there is a better way how to do this and then use fixture?)

So, no fixture available to retrieve service with ...'debugElement.injector...'

When injecting the service, I have another scope, because the spy doesn't react:

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

Any idea how I could bind the scope to the component here or retrieve the service through the component(dialogRef.componentInstance)?

seawave_23
  • 1,169
  • 2
  • 12
  • 23

1 Answers1

4

How I could solve this:

Inside TestComponent, inject MdDialog and set dialogRef:

public dialogRef: MdDialogRef<TestComponent>;

constructor(private dialog: MdDialog, private service: TestService){}

Inside TestComponent.spec, you can get TestService as usual through the fixture

    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();
  });

To set the entryComponents, you can override the BrowserDynamicTestingModule.

Melanie
  • 56
  • 3