2016-10-25 18 views
2

ルーティングを使用するangular2コンポーネントをユニットテストしようとしています。私が持っている:Jasmine route spy - undefinedはオブジェクトではありません( 'navigate.calls.mostRecent()。args'を評価しています)

class MockRouter { 
} 

class MockAuth { 
    isLoggedIn(){ 
    return false; 
    } 
} 

describe('Home',() => { 
    beforeEach(() => TestBed.configureTestingModule({ 
    providers: [ 
     BaseRequestOptions, 
     { provide: Router, useClass: MockRouter }, 
     HomeComponent, 
     { provide: AuthenticationService, useClass: MockAuth } 
    ] 
    })); 

    it('should navigate to login', inject([HomeComponent], (home: HomeComponent) => { 
    let navigate = jasmine.createSpy('navigate'); 
    expect(navigate.calls.mostRecent().args[0]).toEqual(['/login']); 
    })); 
}); 

が、私はエラーを取得しています:

TypeError: undefined is not an object (evaluating 'navigate.calls.mostRecent().args') in config/spec-bundle.js (line 41757)

私はジャスミンのスパイが正しいアプローチであるが、私は私が間違っているの - どのように何かを見逃していると思いますか?

答えて

1

MockRouterクラスにスパイを追加する必要があります。スパイはお知らせRouter

class MockRouter { 
    navigate = jasmine.createSpy('navigate'); 
} 

describe('Home',() => { 
    let mockRouter; 
    let fixture; 
    let component: HomeComponent; 

    beforeEach(() => { 
    mockRouter = new MockRouter(); 
    TestBed.configureTestingModule({ 
     declarations: [ HomeComponent ] 
     providers: [ 
      BaseRequestOptions, 
      { provide: Router, useValue: mockRouter }, 
      { provide: AuthenticationService, useClass: MockAuth } 
     ] 
     }); 
     fixture = TestBed.createComponent(HomeComponent); 
     component = fixture.createComponent; 
    }); 

    it('should navigate to login',() => { 
    // calls component.ngOnInit 
    fixture.detectChanges(); 

    // assuming some navigation has been done 
    expect(mockRouter.navigate).toHaveBeenCalledWith(['/login']); 
    }); 
}); 

navigate通話をスパイしているように:

  • HomeComponentないproviders
  • に我々はテストでモックへの参照を保持し、declarationsであり、構成するときuseClassの代わりにuseValueを使用してください。
関連する問題