Angular 4 - router.url单元测试

时间:2017-09-18 05:09:58

标签: angular unit-testing

如何在角度4单元测试中模拟router.url?

我在我的组件中的ngOnint中使用router.url但在我的测试中,router.url的值是'/'

3 个答案:

答案 0 :(得分:2)

你可以使用jasmine spyObj。 在你TestBed

providers:[
 {
 provide: Router,
 usevalue: jasmine.createSpyObj('Router',['methodOne','methodTwo]),
 },
],

in beforeEach:

router = fixture.debugElement.injector.get(Router);

在测试中:

it('should...', ()=> {
 (router.methodOne as Spy).and.returnValue(whateverValue)// if you wanna mock the response
});

答案 1 :(得分:0)

这听起来像一个解决方案 jasmine angular 4 unit test router.url

body, html {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
}

.menu {
  width: 100%;
  height: 75px;
  background-color: rgba(0, 0, 0, 1);
  position: fixed;
  background-color: rgba(4, 180, 49, 0.6);
  -webkit-transition: all 0.3s ease;
  -moz-transition: all 0.3s ease;
  -o-transition: all 0.3s ease;
  transition: all 0.3s ease;
}

.light-menu {
  width: 100%;
  height: 75px;
  background-color: rgba(255, 255, 255, 1);
  position: fixed;
  background-color: rgba(4, 180, 49, 0.6);
  -webkit-transition: all 0.3s ease;
  -moz-transition: all 0.3s ease;
  -o-transition: all 0.3s ease;
  transition: all 0.3s ease;
}

#menu-center {
  width: 980px;
  height: 75px;
  margin: 0 auto;
  ul {
    margin: 15px 0 0 0;
    li {
      list-style: none;
      margin: 0 30px 0 0;
      display: inline;
    }
  }
}

.active {
  font-family: 'Droid Sans', serif;
  font-size: 14px;
  color: #fff;
  text-decoration: none;
  line-height: 50px;
}

a {
  font-family: 'Droid Sans', serif;
  font-size: 14px;
  color: black;
  text-decoration: none;
  line-height: 50px;
}

#home {
  background-color: grey;
  height: 100%;
  width: 100%;
  overflow: hidden;
}

#portfolio {
  height: 100%;
  width: 100%;
}

#about {
  background-color: blue;
  height: 100%;
  width: 100%;
}

#contact {
  background-color: red;
  height: 100%;
  width: 100%;
}

答案 2 :(得分:0)

在Angular v9中,Router.url是只读的getter属性。您可以强制private属性值设置url属性:

    const mockUrlTree = router.parseUrl('/heroes/captain-marvel');
    // @ts-ignore: force this private property value for testing.
    router.currentUrlTree = mockUrlTree;