[英]Angular 2 testing Router with Jasmine and Karma
我在為 angular 2 中的 router.navigate 編寫存根時遇到問題。我目前編寫了以下存根。 這就是 angular 文檔中顯示的內容。
@Injectable
export class RouterStub {
navigate(commands: any[], extras?: NavigationExtras) { }
但是,當我使用此存根時,出現以下錯誤。
TypeError: this.router.navigate is not a function
我對導航的用法如下。
let summaryLink = ['/summary', this.client.id, this.client.lastName];
this.router.navigate(summaryLink);
任何幫助,將不勝感激。
只是一個更新......我能夠使用我發現這里引用的非 TestBed 方法使這個測試工作。 但是,如果有人能夠弄清楚如何使用 TestBed 方法進行此測試,我將不勝感激。 謝謝
您必須引導您的測試,包括路由器模塊。 這與引導應用程序非常相似:
const IMPORTS: any[] = [
BrowserModule,
...
RouterModule.forRoot(routes)
];
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: IMPORTS,
declarations: DECLARATIONS
providers: PROVIDERS
}).compileComponents();
}));
然后,您可以獲取對路由器的引用。
beforeEach(() => {
router = TestBed.get(Router);
fixture = TestBed.createComponent(YourComponent);
component = fixture.componentInstance;
element = fixture.nativeElement;
});
測試狀態(需要依賴,因為組件被渲染等等):
it('routes to the dummy component', fakeAsync(() => {
tick(1000);
fixture.detectChanges();
router.navigate(['dummy']);
tick(1000);
fixture.detectChanges();
expect(router.isActive('/dummy', true)).toBe(true);
}));
通信測試(不路由;我們只需要驗證導航是否真的發生了):
it('routes to the dummy component', fakeAsync(() => {
spyOn(router, 'navigate').and.callFake(() => {});
tick(1000);
fixture.detectChanges();
router.navigate(['dummy']);
tick(1000);
fixture.detectChanges();
expect(router.navigate).toHaveBeenCalledWith(['dummy']);
}));
在實際測試中,您不會測試 navigate() 方法。 實際上,您將要測試某種用戶行為,例如單擊:
在組件中(在本例中為 YourComponent):
onClick() {
this.router.navigate(['dummy']);
}
在測試中(用點擊觸發器替換navigate()):
element.querySelector('button').click();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.