import { RouterTestingModule } from '@angular/router/testing';
...
beforeEach(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule],
...
}).compileComponents();
});
import { Router } from '@angular/router';
...
it('should navigate to /home', inject([Router], (router: Router) => {
const navigateSpy = spyOn(router, 'navigateByUrl');
component.goToHome();
expect(navigateSpy).toHaveBeenCalledWith('/home');
}));
上面的示例中,我们在组件中定义了一个名为goToHome的方法,用于导航到/home路由。
这样通过设置RouterTestingModule模块并注入Router服务就可以在Angular单元测试中设置当前路由啦!
上一篇:Angular单元测试中ng-template触发器在按钮点击后不起作用
下一篇:Angular单元测试中Testbed.inject(serviceName)和fixture.debugElement.injector.get(serviceName)有什么区别?