角度测试:无法读取null的属性“ nativeElement”

时间:2019-10-15 15:05:08

标签: angular integration-testing karma-runner angular-routerlink

我是Angular测试的新手,此刻正在尝试测试这段代码,但是在DOM上引发的事件方面遇到了错误:

<li class="list-group-item" *ngFor="let user of users">
  <a class="test-link"[routerLink]="['/detail', user.id]">
    {{user.userName}}
  </a>
</li>

测试文件:

beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [AdminComponent, UserDetailComponent],
    imports: [HttpClientModule,RouterTestingModule.withRoutes([
      {path:'detail/:id',
        component: UserDetailComponent}],
    )],
    providers: [UserService, AuthService]
  })
    .compileComponents();
}));

beforeEach(() => {
  router = TestBed.get(Router);
  location = TestBed.get(Location);

  fixture = TestBed.createComponent(AdminComponent);
  debugElement = fixture.debugElement;
  component = fixture.componentInstance;
  fixture.detectChanges();

});

it('test demands redirection', fakeAsync(() => {

  debugElement
    .query(By.css('.test-link'))
    .nativeElement.click();

  tick();

  expect(location.path()).toBe('/detail/testing/1');

}));

为什么原生元素上的click事件为空?

2 个答案:

答案 0 :(得分:2)

这是因为运行此测试时,您的users数组将为空,因此使用.test-link选择器的html中将没有任何元素。

在单击元素之前,应填充users数组,并让angular运行更改检测,以便在单击锚标记时可用。

代码:

it('test demands redirection', fakeAsync(() => {

  component.users = [
    // fill it with user objects
  ];

  fixture.detectChanges();

  debugElement
    .query(By.css('.test-link'))
    .nativeElement.click();

  tick();

  expect(location.path()).toBe('/detail/testing/1');

}));

答案 1 :(得分:0)

我遇到了相同的错误-“ TypeError:无法读取null的'nativeElement'属性”-并发现我已将同一HTML元素ID复制粘贴到多个位置。我保证

相关问题