Angular单元测试:如何测试routerLink?

6
如何测试routerLink?
我尝试使用以下方法:
beforeEach(() => {
    fixture = TestBed.createComponent(HomeComponent);
    component = fixture.componentInstance;
    debugEl = fixture.debugElement;
    element = debugEl.nativeElement;
    fixture.detectChanges();
  });
  it('should have href with /login', () => {
    fixture.detectChanges();
    const href = debugEl.query(By.css('a')).nativeElement.getAttribute('href');
    console.error(href) // give me null 
    //expect(expect(href)).toEqual('/login');
  });

但是 href 变量为空。 我也尝试了 .nativeElement.href 但是返回了一个空字符串。

您是否已将RoutingModule导入到测试模块中? - phenomnomnominal
2个回答

19
为了编译 routerLink 指令,需要将路由模块(更具体地说,是其测试版本,因为真实的路由不应在测试中发生)导入到测试平台中:

为了在 test bed 中编译 routerLink 指令,需要导入路由模块(更具体地说,是其测试版本,因为真实的路由不应在测试中发生):

import { RouterTestingModule } from '@angular/router/testing';

...

TestBed.configureTestingModule({
  imports: [RouterTestingModule]
});

考虑到组件模板中有<a routerLink="/login"></a>,那么这应该是正确的:

const href = debugEl.query(By.css('a')).nativeElement.getAttribute('href');
expect(expect(href)).toEqual('/login');

考虑到routerLink可接受复杂配置,href断言可能不足够。尽管它依赖于应该值得信任的RouterTestingModule,但它是黑盒测试。

一种更具体的方法是测试routerLink输入本身。考虑到组件模板中存在<a [routerLink]="['/login']"></a>并且已经导入了RouterTestingModule,这应该是正确的:

import { RouterLinkWithHref } from '@angular/router';

...

const linkDebugEl = debugEl.query(By.css('a'));
const routerLinkInstance = linkDebugEl.injector.get(RouterLinkWithHref);
expect(routerLinkInstance['commands']).toEqual(['/login']);
expect(routerLinkInstance['href']).toEqual('/login');

如果需要测试 commands 输入,可以通过替换适当的虚拟指令来代替 RouterLink 指令,这样就不需要使用 RouterTestingModule 了。


3
你需要监视路由器。
const router = TestBed.get(router); //Get the router from the TestBed.
const spy = spyOn(router, 'navigate'); //Register a Spy on the router navigate function

expect(spy).toHaveBeenCalledWith(['login']); //Check if the router has been called with 'login'

在测试中,您应该使用RouterTestingModule而不是应用程序的路由。

路由测试模块

如果需要,您可以设置自己的路由。(来自Angular测试文档)

 beforeEach(() => {
  TestBed.configureTestModule({
    imports: [
      RouterTestingModule.withRoutes(
       [{path: '', component: BlankCmp}, {path: 'simple', component: SimpleCmp}])]
      )
    ]
  });
});

请查看Angular测试的更多信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接