在Angular中进行单元测试时,可以使用Angular的内置测试工具 TestBed 和 RouterTestingModule 来测试 routerLink 的状态。
首先,需要导入必要的模块和组件:
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { Component } from '@angular/core';
接下来,创建一个测试用的组件,该组件包含一个带有 routerLink 的链接元素:
@Component({
template: `
Home
`
})
class TestComponent {
activeClass: string;
}
然后,编写测试用例:
describe('TestComponent', () => {
let fixture: ComponentFixture;
let component: TestComponent;
let linkElement: HTMLElement;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule],
declarations: [TestComponent]
});
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
linkElement = fixture.nativeElement.querySelector('a');
});
it('should have routerLink active state', () => {
component.activeClass = 'active';
fixture.detectChanges();
expect(linkElement.classList.contains('active')).toBe(true);
});
it('should not have routerLink active state', () => {
component.activeClass = 'active';
fixture.detectChanges();
expect(linkElement.classList.contains('active')).toBe(false);
});
});
在上面的测试用例中,我们首先设置 activeClass 为 'active',然后检查链接元素是否含有 'active' 类。第一个测试用例预期结果应为 true,而第二个测试用例预期结果应为 false。
最后,运行测试用例:
ng test
这样就可以测试 routerLink 的状态了。