4

我是 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');

}));

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

4

2 回答 2

6

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

在单击元素之前,您应该填充 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');

}));
于 2019-10-15T15:35:18.357 回答
0

我遇到了同样的错误——“TypeError: Cannot read property 'nativeElement' of null”——发现我已将相同的 html 元素 ID 复制粘贴到多个位置。我保证

于 2020-12-04T17:18:32.617 回答