茉莉花角4单元测试router.url [英] jasmine angular 4 unit test router.url

查看:82
本文介绍了茉莉花角4单元测试router.url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jasmine对angular 4项目中的功能进行单元测试,如下所示:switch语句:

I am unit testing a function in angular 4 project using jasmine which a switch statement like mentioned below:

    switch(this.router.url) {

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

    }

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

In my spec.ts file. I can't stub or change the value of router.url.I want my cases to execute but default is executing. I tried different ways to set or spyOn and return value, but everytime url is '/'. Every suggestion or solution will be welcomed.

推荐答案

首先,您需要在测试模块中模拟路由器:

First you need to mock router in your testing module:

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

您还可以在测试中更改URL并运行已测试的方法:

You can also change the url in the test and run your tested method:

const router = TestBed.get(Router);
router.url = '/path/to/anything';
// now you can run your tested method:
component.testedFunction();

正如您提到的,spyOn不起作用,因为它仅适用于方法/功能.但是url是属性.

As you mention spyOn doesnt work because it works only for methods/functions. But url is a property.

这篇关于茉莉花角4单元测试router.url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆