1

I have a simple test:

it ('should be able to navigate to add program', fakeAsync(() => {
  let href = fixture.debugElement.query(By.css('.add-program-btn'));
  let link = href.nativeElement.getAttribute('href');
  expect(link).toEqual('/program/new');
}));

And keep getting an error:

TypeError: Cannot read property 'nativeElement' of null

I've tried using tick() with like 20000, and adding fixture.detectChanges() but nothing works. Another test that checks if a button was clicked and a function called has the same error. Is it that it can't find the element?

Everything this test is using is in Angular so I don't think it's because it's a hybrid app.

Thanks in advance.

Edgar Quintero
  • 4,223
  • 2
  • 34
  • 37
  • Try `console.log(fixture.debugElement.nativeElement.innerHTML)` to see what the HTML looks like. – Reactgular May 28 '19 at 18:54
  • Ok, thanks. Seems like the root of the problem is an `ngIf` that I have in the parent container. So now what should I do, set whatever the `ngIf` to true so that the correct HTML is in the DOM ? – Edgar Quintero May 28 '19 at 19:12
  • However, now I get `TypeError: Cannot read property 'length' of undefined` – Edgar Quintero May 28 '19 at 19:19

1 Answers1

2

This happens when *ngIf is being used in the template and it's expression evaluates to a falsy value. You should set appropriate inputs to the component so that *ngIf can evaluate to true;

Here is some sample code:

it ('should be able to navigate to add program', async(() => {
  const component = fixture.componentInstance;

  // Set particular input so that ngIf makes your href visible to true
  component.inputName = true;

  // run change detection, updated input value should get used
  fixture.detectChanges();

  // in some cases you may want for things to stabilize
  await fixture.whenStable();

  // For debugging prupose, you may want to log innerHTML
  console.log(fixture.debugElement.nativeElement.innerHTML)

  // Rest of the test
  let href = fixture.debugElement.query(By.css('.add-program-btn'));
  let link = href.nativeElement.getAttribute('href');

  expect(link).toEqual('/program/new');
}));
pankaj28843
  • 2,458
  • 17
  • 34