【问题标题】:jasmine angular 4 unit test router.url茉莉角 4 单元测试 router.url
【发布时间】:2019-04-18 05:52:11
【问题描述】:

我正在使用 jasmine 对 angular 4 项目中的一个函数进行单元测试,其中一个 switch 语句如下所述:

    switch(this.router.url) {

    case 'firstpath': {
               // some code
            }
        break;
    case 'secondpath': {
               // some more code
            }
       break;
    default:
        break;

    }

在我的 spec.ts 文件中。我无法存根或更改 router.url 的值。我希望我的案例执行,但默认正在执行。我尝试了不同的方法来设置或 spyOn 和返回值,但每次 url 都是'/'。每个建议或解决方案都将受到欢迎。

【问题讨论】:

    标签: angular unit-testing karma-jasmine router


    【解决方案1】:

    首先你需要在你的测试模块中模拟路由器:

    TestBed.configureTestingModule({
      ...
      providers: [
        {
           provide: Router,
           useValue: {
              url: '/path'
           } // you could use also jasmine.createSpyObj() for methods
        } 
      ]
    });
    

    您也可以在测试中更改 url 并运行您测试的方法:

    const router = TestBed.inject(Router);
    // @ts-ignore: force this private property value for testing.
    router.url = '/path/to/anything';
    // now you can run your tested method:
    component.testedFunction();
    

    正如您提到的 spyOn 不起作用,因为它仅适用于方法/函数。但是url 是一个属性。

    【讨论】:

    • @martin 你是我的救星!我尝试使用spyOnProperty(spyRouter, 'url', 'get').and.returnValue('test');,但它并没有那么安静地锻炼。
    • 使用 router.url = '/path/to/anything' 时出现错误“TypeError: Cannot set property url of [object Object] which has only a getter”
    • 如果您收到 Christoper Grigg 评论中的错误,则路由器可能无法正确模拟。您可以尝试spyOnProperty 并将其用作spyOnProperty(router, 'url', 'get').and.returnValue('yourUrl')
    • 我们可以用RouterTestingModule做类似的事情吗?
    • @MartinNuc,非常感谢您的回答。它也解决了我的路由器juni测试问题。
    【解决方案2】:

    对于使用 Angular 9 及更高版本的人来说,属性 url 现在是只读属性,因此 spyOnProperty 将不起作用。这也令人困惑,因为您不会收到错误消息,但您也不会看到任何“间谍”。

    要解决这个问题,请使用以下代码:

    const mockUrlTree = routerSpy.parseUrl('/mynewpath/myattribute');
    // @ts-ignore: force this private property value for testing.
    routerSpy.currentUrlTree = mockUrlTree;
    

    感谢 Rob 在此帖子中的回答:

    https://stackoverflow.com/a/63623284/1774291

    【讨论】:

      猜你喜欢
      • 2021-09-16
      • 2020-08-19
      • 1970-01-01
      • 2016-06-14
      • 1970-01-01
      • 2020-12-22
      • 2020-07-22
      • 2017-09-27
      相关资源
      最近更新 更多