gpt4 book ai didi

Angular Testing : Cannot read property 'nativeElement' of null

转载 作者:行者123 更新时间:2023-12-04 02:43:08 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com