在Angular单元测试中使用路由器的方法如下:
import { RouterTestingModule } from '@angular/router/testing';
import { Router } from '@angular/router';
import { Location } from '@angular/common';
TestBed.configureTestingModule({
imports: [RouterTestingModule]
});
let router: Router;
let location: Location;
beforeEach(() => {
router = TestBed.inject(Router);
location = TestBed.inject(Location);
});
it('should navigate to /home', fakeAsync(() => {
router.navigate(['/home']);
tick();
expect(location.path()).toBe('/home');
}));
在以上示例中,我们使用router.navigate
方法导航到/home
路径,并使用location.path()
断言当前路径是否为/home
。
这样,你就可以在单元测试中使用路由器来测试导航、URL等路由相关的功能了。