Angular Testing : Cannot read property 'nativeElement' of null

标签 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');

}));

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

最佳答案

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

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

代码:

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

}));

关于 Angular Testing : Cannot read property 'nativeElement' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58397719/

相关文章:

javascript - 云FireStore : Retrieve 1 document with query

integration-testing - 机器人框架 : assign variable with if-else statement

unit-testing - 我们如何决定可以使用哪种测试方法?

java - 在集成测试之前使用 Maven 运行 Jetty

javascript - 为在 Karma 中执行整页重新加载的指令编写测试

sonarqube - LCOV.INFO 有 SF 的绝对路径

unit-testing - 单元测试 typescript 指令模板 karma-jasmine,未定义 html

html - 如何仅在悬停子菜单时显示子菜单项?

css - CSS 中的 Angular Material 2 目标元素

angular - 将以前的值与输出发射器和 ValueChanges 进行比较