jeudi 5 octobre 2017

Angular4 testing, why use DebugElement

So while I was creating an test for my front-end application I encountered something weird.

The tutorial does something like this:

de = fixture.debugElement.query(By.css('h2'));
el = de.nativeElement;

Unfortunately this fails for me. My tests tell me that EL becomes null. However when I do not use the debugelement it works. (a bit modified) Code:

el = fixture.nativeElement.querySelector('h2');

Whole spec.ts file (perhaps the error lies elsewhere):

describe('ModuleOverviewComponent', () => {
  let component: ModuleOverviewComponent;
  let fixture: ComponentFixture<ModuleOverviewComponent>;
  let de:      DebugElement;
  let el:      HTMLElement;
  let backendService;
  let spy;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ HttpModule,
                  InMemoryWebApiModule.forRoot(InMemoryDataService)],
      declarations: [ ModuleOverviewComponent ],
      providers: [BackendService]
    })
    .compileComponents();

  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ModuleOverviewComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

    backendService = fixture.debugElement.injector.get(BackendService);
    spy = spyOn(backendService, 
'getSemesters').and.returnValues(Promise.resolve(semesters));
    de = fixture.debugElement.query(By.css('h2'));
    el = fixture.nativeElement.querySelector('h2');
  });

  it('should show semester 1 after the data is send', async(() => {
    fixture.detectChanges();

    fixture.whenStable().then(() => { // wait for async getQuote
      fixture.detectChanges();        // update view with quote
      expect(el.innerText).toBe('Semester 1');
    });
  }));
});

I was reading: http://ift.tt/2xv89Cn

chapter:Test a component with an async service

The test works with this setup. But perhaps someone can tell me why debugelement doesn't work. And if you know what's wrong, why use debugelement in the first place.

Aucun commentaire:

Enregistrer un commentaire