2

我測試使用的RouteLink指令,像這樣一個組件:RouteLink測試angular2

let comp: AppComponent; 
let fixture: ComponentFixture<AppComponent>; 
let el: DebugElement; 
let injector: Injector; 
let languageService: TranslateService; 
let location: Location; 
let backend: MockBackend; 
let connection: MockConnection; // this will be set when a new connection is emitted from the backend. 

let mockRouter: any; 
let mockActivatedRoute: any; 
const mockBackendResponse = (connection: MockConnection, response: string) => { 
    connection.mockRespond(new Response(new ResponseOptions({ body: response }))); 
}; 
describe('testComponent',() => { 
    beforeEach(() => { 
    TestBed.configureTestingModule({ 
     declarations: [AppComponent], 
     imports: [HttpModule, RouterTestingModule, TranslateModule.forRoot({ 
     provide: TranslateLoader, 
     useFactory: (http: Http) => new TranslateStaticLoader(http, './assets/language', '.json'), 
     deps: [Http] 
     })], 
     providers: [ 
     { provide: LanguageService, useClass: LanguageService }, 
     { provide: BackendLocatorService, useClass: BackendLocatorService }, 
     { provide: XHRBackend, useClass: MockBackend }, 
     { provide: APP_BASE_HREF, useValue: '/' } 
     ] 
    }); 

    injector = getTestBed(); 
    backend = injector.get(XHRBackend); 
    languageService = injector.get(TranslateService); 
    location = injector.get(Location); 

    backend.connections.subscribe((c: MockConnection) => connection = c); 
    fixture = TestBed.createComponent(AppComponent); 
    comp = fixture.componentInstance; // BannerComponent test instance 
    // get title DebugElement by element name 
    }); 
    it('is defined',() => { 
    expect(TranslateService).toBeDefined(); 
    expect(languageService).toBeDefined(); 
    expect(languageService instanceof TranslateService).toBeTruthy(); 
    }); 

    it('ROUTLINK CLICK',() => { 
    fixture.detectChanges(); 
    let links = fixture.nativeElement.querySelectorAll('a'); 
    links[1].click(); 
    console.log(links[0]); 
    expect(location.path()).toBe('/home'); 
    }); 
}); 

我試圖讓<a>標籤,爲了得到當前路徑點擊它,但問題是,當前路徑總是',沒有什麼:( 這裏是錯誤:

Chrome 53.0.2785 (Windows 7 0.0.0) testComponent ROUTLINK CLICK FAILED 
Expected '' to be '/home'. 

任何想法

回答

3

所以,你有一個當前的錯誤,並且在你修復之後,你會得到另一個錯誤。

當前錯誤Expected '' to be '/home'是因爲錨點上的click()涉及異步事件處理。但是你的期望是同步的,並且在異步操作完成之前發生在click()之後。

爲了解決這個問題,你可以讓測試async,然後click()後,你可以通過調用 fixture.whenStable()

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

        // use async 
it('ROUTLINK CLICK', async(() => { 
    fixture.detectChanges(); 
    let links = fixture.nativeElement.querySelectorAll('a'); 
    links[1].click(); 
    fixture.whenStable().then(() => { 
    expect(location.path()).toBe('/home'); 
    }); 
})); 

一旦你解決這個問題,你會遇到另一個問題等待異步操作。目前,您沒有爲RouterTestingModule配置路由。通過撥打RouterTestingModule.withRoutes(Routes)進行設置。你可以使用你真實的應用程序路線,或者如果你想要的話,建立一些虛假的路線進行測試。 See example

+0

謝謝你的工作 – user3518668