单击链接时如何测试路由器导航到正确的组件

时间:2019-02-12 22:12:42

标签: angular

我有一个包含以下html的组件。

<div id="invalid-page-grid-container">
  <div id="invalid-page-h1">
    <h1>Oops!</h1>
  </div>
  <div id="invalid-page-para">
    <h6 id="header-link-to-homepage">The Page you are looking for does not exist! Click <a id="homepage-link" [routerLink]="homepageRouterLink"> here </a> to go back to home page of the application !</h6>
  </div>
</div>

我要对单击<a>的路由器进行单元测试,路由器导航到HomePAgeComponent。我该怎么办?

我已经编写了以下测试用例,但失败了。

  fit('clicking on home page link should redirect to home page controller',()=>{
    let homepageLinkDE:DebugElement = fixture.debugElement.query(By.css("#homepage-link"));
    let location:SpyLocation = TestBed.get(Location);
    expect(homepageLinkDE).toBeTruthy();
    let homepageLinkNE:HTMLElement = homepageLinkDE.nativeElement;
    homepageLinkNE.click();
    console.log("location is ",location);
    console.log("url is ",location.urlChanges);
    expect(location.urlChanges.length).toEqual(1); //this is 0

      });

有趣的是,我在跟踪中注意到urlChanges数组实际上有1个元素。我不知道为什么测试用例失败了

location is  SpyLocation {urlChanges: Array(0), _history: Array(1), _historyIndex: 0, _subject: EventEmitter, _baseHref: "", …}urlChanges: Array(1)0: "/home"length: 1__proto__: Array(0)_baseHref: ""_history: Array(2)0: LocationState {path: "", query: "", state: null}1: LocationState {path: "/home", query: "", state: {…}}length: 2__proto__: Array(0)_historyIndex: 1_platformStrategy: null_subject: EventEmitter {_isScalar: false, observers: Array(0), closed: false, isStopped: false, hasError: false, …}__proto__: Object
context.js:1972 url is  []0: "/home"length: 1__proto__: Array(0)

1 个答案:

答案 0 :(得分:0)

我忘记了导航是异步的。我在代码中添加了一个等待,现在一切正常。我发现chrome的控制台中有打印Value below was evaluated just now”

后才发现
fit('clicking on home page link should redirect to home page controller',(done)=>{
    let homepageLinkDE:DebugElement = fixture.debugElement.query(By.css("#homepage-link"));
    //let router = TestBed.get(Router);
    let location:SpyLocation = TestBed.get(Location);
    expect(homepageLinkDE).toBeTruthy();
    let homepageLinkNE:HTMLElement = homepageLinkDE.nativeElement;
    homepageLinkNE.click();
    //router.navigate(["/home"]);
    //let snapshop = TestBed.get(ActivatedRouteSnapshot);
    setTimeout(()=> {
      console.log("location is ", location);
      console.log("url is ", location.urlChanges);
      expect(location.urlChanges.length).toEqual(1);
      expect(location.urlChanges[0]).toEqual("/home");
      done();
    },1000);

      });