我是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?
这是因为在运行此测试时,你的users数组将为空,因此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');
}));
感谢您的回答,但是我可以用伪数据填充它吗?
是的,您可以使用所需的任何数据填充它。