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

问题描述 投票:0回答:1

我是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?

angular integration-testing karma-runner angular-routerlink
1个回答
1
投票

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

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

}));
© www.soinside.com 2019 - 2024. All rights reserved.