Warm tip: This article is reproduced from serverfault.com, please click

其他- Angular 测试:无法读取null的属性“ nativeElement”

(其他 - Angular testing: Cannot read property 'nativeElement' of null)

发布于 2019-10-15 15:05:08

我是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事件为null?

Questioner
Mellville
Viewed
11
Archit Garg 2019-10-15 23:35:18

这是因为在运行此测试时,你的users数组将为空,因此html中没有带.test-link选择器的元素

在单击元素之前,应填充用户数组,并让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');

}));