Mel*_*lle 3 integration-testing karma-runner angular 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>
Run Code Online (Sandbox Code Playgroud)
测试文件:
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');
}));
Run Code Online (Sandbox Code Playgroud)
为什么本机元素上的点击事件为空?
小智 5
这是因为当此测试运行时,您的 users 数组将为空,因此 html 中将没有带有.test-link选择器的元素。
在单击元素之前,您应该填充 users 数组并让 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');
}));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15047 次 |
| 最近记录: |