Angular 测试:无法读取 null 的 属性 'nativeElement'
Angular testing: Cannot read property 'nativeElement' of null
我是 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');
}));
为什么原生元素的点击事件为空?
这是因为当此测试将 运行 时,您的用户数组将为空,因此 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');
}));
我遇到了同样的错误——“TypeError: Cannot read 属性 'nativeElement' of null”——并且发现我已经将相同的 html 元素 id 复制粘贴到多个位置.我保证
我是 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');
}));
为什么原生元素的点击事件为空?
这是因为当此测试将 运行 时,您的用户数组将为空,因此 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');
}));
我遇到了同样的错误——“TypeError: Cannot read 属性 'nativeElement' of null”——并且发现我已经将相同的 html 元素 id 复制粘贴到多个位置.我保证