【问题标题】:how to unit test router.navigate in angular app如何在 Angular 应用程序中对 router.navigate 进行单元测试
【发布时间】:2019-09-10 10:27:17
【问题描述】:

我正在为 Angular 应用程序运行单元测试,如果导航在 Angular 应用程序中正常工作,我想进行单元测试。

 if (this.customer.length == 0) {
     this.router.navigate(['/nocustomer']);
 } 

以及对此的单元测试

 it(`should navigate to nocustomer`,()=>{
   component.customers.length=0;
   //what must be written here to check this
})

【问题讨论】:

  • 查看有关测试路由器的 Angular 文档。 angular.io/guide/testing#routing-component。一般的策略是使用 jasmine 创建一个间谍对象,并在测试中使用该间谍对象。
  • @Karthik_personal 检查答案

标签: angular unit-testing router navigateurl


【解决方案1】:

有时,我会动态地将其他参数用于调用导航。所以,只期望我在测试中使用的路径:

...
test('Navigate to /nextPage.', inject([Router], (mockRouter: Router) => {

  const spy = spyOn(mockRouter, 'navigate').and.stub();

  component.goToNextPageMethod();

  expect(spy.calls.first().args[0]).toContain('/nextPage');

}));
...

参考:https://semaphoreci.com/community/tutorials/testing-routes-in-angular-2

【讨论】:

    【解决方案2】:

    查看unit testing router in Angular

    执行以下操作

    1) 从@angular 导入路由器。

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

    2) 将路由器添加到您的 providers 数组并将其换成 routerSpy。

    TestBed.configureTestingModule({
      providers: [
        { provide: Router, useValue: routerSpy }
      ]
    })
    

    3) 最后创建routerSpy,并创建一个jasmine spy来观察navigation方法。

    let routerSpy = {navigate: jasmine.createSpy('navigate')};
    

    当测试运行时组件找不到<router-outlet></router-outlet> 元素时,这将阻止您的单元测试失败。

    然后您可以使用以下方法测试 router.navigate() 是否已被调用:

    expect (routerSpy.navigate).toHaveBeenCalledWith(['/nocustomer']);
    

    因此,如下修改您的 it() 语句并添加以上内容 配置

    it(`should navigate to nocustomer`, () => {
       component.customers = [];
       expect (routerSpy.navigate).toHaveBeenCalledWith(['/nocustomer']);
    });
    

    【讨论】:

    • OP 正在询问如何模拟导航而不是对导航做出断言。
    • 在 Angular 中进行单元测试时,我们不检查 Angular 的路由器导航是否正确,而是检查我们的实现,因此我们测试我们编写的代码是否符合我们的预期。
    • 但是您实际上正在检查它是否通过您对toHaveBeenCalledWith 的调用正确导航。 OP 正在询问如何对被测对象的行为进行导航和断言。 OP 不会询问是否已调用导航。
    • OP 在哪里询问如何导航? OP 请求,我想对导航是否正常工作进行单元测试,并且它阻止状态“应该导航到 nocustomer”,因此 toHaveBeenCalledWith 的使用检查是否使用正确的 url 调用它,如果测试通过则意味着导航成功,它导航到 nocustomer,如果您根据自己的理解有不同的解决方案或不同的期望,请将其作为建议、评论或答案。
    猜你喜欢
    • 2016-04-05
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 2019-11-02
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2012-03-21
    相关资源
    最近更新 更多