角度混合应用程序测试“无法读取null的属性'nativeElement'”

时间:2019-05-28 18:37:52

标签: angular angular-testing angular-hybrid

我有一个简单的测试:

function sampleScriptRunning(activity) {
  const IDArray = activity.map({
    ID
  } => ID);
  const postResponses = [];

  (asnyc() => {
    for (let id of IDArray) {
      let response = await Api.getActivityStatus(id);
      let postResponse = await $http.post('/proxy/api/nodejsjob/' + response.sample.sample[0].ScriptId + '/run');
      postResponses.push(postResponse);
    }
    return postResponses;
  })();
}

并不断出现错误:

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

我尝试将TypeError: Cannot read property 'nativeElement' of null tick()一起使用,并添加20000,但没有任何效果。另一个检查按钮是否被单击且调用的函数具有相同错误的测试。是找不到元素吗?

该测试使用的所有内容都在Angular中,所以我不认为这是因为它是一个混合应用程序。

谢谢。

1 个答案:

答案 0 :(得分:0)

在模板中使用*ngIf且表达式的表达式计算为假值时会发生这种情况。您应该为组件设置适当的输入,以便*ngIf可以得出true;

以下是一些示例代码:

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