我有一个组件,它是带有路由器链接的简单 disabled 锚点
@Component({
template: `<a [routerLink]="target" disabled>click me</a>`,
})
class DisabledLinkComponent {
target = '/destination';
}
我想使用RouterTestingModule
来测试单击锚点时位置不变。
@Component({ template: '' })
class FakeComponent {}
describe('DisabledLinkComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule.withRoutes([{ path: 'destination', component: FakeComponent }])],
declarations: [DisabledLinkComponent, FakeComponent],
}).compileComponents();
}));
it('should not change location when clicked', () => {
const fixture = TestBed.createComponent(DisabledLinkComponent);
fixture.detectChanges();
fixture.nativeElement.querySelector('a').click();
expect(TestBed.get(Location).path()).not.toBe('/destination');
});
});
但是期望失败了。我的测试方式有什么问题?
答案 0 :(得分:1)
jonrsharpe是正确的,您的禁用属性无法正常工作。
检出this reply是禁用锚点的正确方法。
尽管如此,为了进行适当的Location.path()评估,您需要使用whenStable将其包装起来:
fixture.whenStable().then(() => {
expect(TestBed.get(Location).path()).not.toBe('/destination');
});
答案 1 :(得分:0)
因此,如果您希望锚点在单击时不起作用,那么我认为最好的选择是将routerLink设置为null
。
import { Location } from '@angular/common';
import { Component } from '@angular/core';
import { async, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
@Component({
template: `
<a [routerLink]="disabled ? null : target">click me</a>
`,
})
class LinkComponent {
target = '/destination';
disabled = true;
}
@Component({ template: '' })
class FakeComponent {}
describe('DisabledLinkComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule.withRoutes([{ path: 'destination', component: FakeComponent }])],
declarations: [LinkComponent, FakeComponent],
}).compileComponents();
}));
it('should not change location when disabled and clicked', async () => {
const fixture = TestBed.createComponent(LinkComponent);
fixture.componentInstance.disabled = true;
fixture.detectChanges();
fixture.nativeElement.querySelector('a').click();
await fixture.whenStable();
expect(TestBed.get(Location).path()).not.toBe('/destination');
});
it('should change location when not disabled and clicked', async () => {
const fixture = TestBed.createComponent(LinkComponent);
fixture.componentInstance.disabled = false;
fixture.detectChanges();
fixture.nativeElement.querySelector('a').click();
await fixture.whenStable();
expect(TestBed.get(Location).path()).toBe('/destination');
});
});