2016-09-30 70 views
14

在Angular 2.0.0中,我正在對使用Router的組件進行單元測試。但是,我得到'提供的參數不匹配調用目標的任何簽名'。錯誤。在spec.ts的Visual Studio代碼中,它是以紅色突出顯示的新路由器()Angular 2 - 使用路由器進行單元測試

我真的很感激,如果有人能讓我知道正確的語法是什麼嗎?提前致謝。我的代碼如下:

spec.ts

import { TestBed, async } from '@angular/core/testing'; 
import { NavToolComponent } from './nav-tool.component'; 
import { ComponentComm } from '../../shared/component-comm.service'; 
import { Router } from '@angular/router'; 

describe('Component: NavTool',() => { 
    it('should create an instance',() => { 
    let component = new NavToolComponent(new ComponentComm(), new Router()); 
    expect(component).toBeTruthy(); 
    }); 
}); 

組件構造

constructor(private componentComm: ComponentComm, private router: Router) {} 

回答

8

這是因爲Route有一定的依賴性,預計傳遞給它的構造。

如果您使用的是Angular組件,則不應該嘗試執行獨立測試。您應該使用Angular測試基礎架構來準備測試環境。這意味着讓Angular創建組件,讓它注入所有必需的依賴關係,而不是嘗試創建所有內容。

爲了讓您一開始,你應該有類似

import { TestBed } from '@angular/core/testing'; 

describe('Component: NavTool',() => { 
    let mockRouter = { 
    navigate: jasmine.createSpy('navigate') 
    }; 
    beforeEach(() => { 
    TestBed.configureTestingModule({ 
     declarations: [ NavToolComponent ], 
     providers: [ 
     { provide: Router, useValue: mockRouter }, 
     ComponentComm 
     ] 
    }); 
    }); 
    it('should click link',() => { 
    let fixture = TestBed.createComponent(NavToolComponent); 
    fixture.detectChanges(); 
    let component: NavToolComponent = fixture.componentInstance; 
    component.clickLink('home'); 
    expect(mockRouter.navigate).toHaveBeenCallWith(['/home']); 
    }); 
}); 

或者類似的東西。您可以使用TestBed從零開始配置模塊以進行測試。您使用@NgModule進行幾乎相同的配置。

在這裏,我們只是嘲笑路由器。由於我們只是單元測試,我們可能不需要真正的路由設施。我們只是想確保它被稱爲正確的參數。模擬和spy將能夠捕捉到我們的呼叫。

如果想用真實的路由器,那麼你就需要使用RouterTestingModule,在那裏你可以配置路由。看一個例子herehere

另請參見:

34

您也可以只使用RouterTestingModule,只是spyOn這樣的導航功能...

import { TestBed } from '@angular/core/testing'; 
import { RouterTestingModule } from '@angular/router/testing'; 

import { MyModule } from './my-module'; 
import { MyComponent } from './my-component'; 

describe('something',() => { 

    let fixture: ComponentFixture<LandingComponent>; 

    beforeEach(() => { 

     TestBed.configureTestingModule({ 
      imports: [ 
       MyModule, 
       RouterTestingModule.withRoutes([]), 
      ], 
     }).compileComponents(); 

     fixture = TestBed.createComponent(MyComponent); 

    }); 

    it('should navigate',() => { 
     let component = fixture.componentInstance; 
     let navigateSpy = spyOn((<any>component).router, 'navigate'); 

     component.goSomewhere(); 
     expect(navigateSpy).toHaveBeenCalledWith(['/expectedUrl']); 
    }); 
}); 
+3

謝謝,這個作品!我還使用'router = TestBed.get(Router)'並將路由器保存到燈具旁邊的變量中,而不是將組件轉換爲任何形式,正如https://angular.io/guide/testing#testbedget中所推薦的那樣 –

+0

謝謝你 - 它的工作原理:) – ICantSeeSharp

+0

謝謝,這解決了我的問題:無法讀取嘲弄路由器時未定義的屬性「根」。 –