2016-07-08 21 views
2

這有點令人困惑,因爲我找不到有關Angular 2.0和Router-deprecated文檔中的任何相關內容(是的,我必須在我的項目中使用它)。如何單元測試包含路由器廢棄版本的Angular 2.0服務?

我的服務是這樣的:

import { Injectable } from '@angular/core'; 
import { Http, Headers } from '@angular/http'; 
import { AuthHttp , JwtHelper } from 'angular2-jwt'; 
import { Router } from '@angular/router-deprecated'; 
import { UMS } from '../common/index'; 

@Injectable() 
export class UserService { 

    constructor(
    private router: Router, 
    private authHttp: AuthHttp, 
    private http: Http) { 

     this.router = router; 
     this.authHttp = authHttp; 
     this.http = http; 
    } 

    login(v) { 
     this.http.post(myUrl) 
     .subscribe(
     data => this.loginSuccess(data), 
     err => this.loginFailure(err) 
    ); 
    } 

} 

而且我的測試是這樣的(不真正關心的「它」部分現在):

import { Http } from '@angular/http'; 
import { AuthHttp, JwtHelper } from 'angular2-jwt'; 
import { Router } from '@angular/router-deprecated'; 
import { 
    beforeEach, beforeEachProviders, 
    describe, xdescribe, 
    expect, it, xit, 
    async, inject 
} from '@angular/core/testing'; 
import { UserService } from './user.service'; 

describe('User Service',() => { 

    let service; 

    beforeEachProviders(() => [ 
    Router, 
    AuthHttp, 
    Http, 
    UserService 
    ]); 

    beforeEach(inject([ 
     Router, 
     AuthHttp, 
     Http, 
     UserService], s => { 
    service = s; 
    })); 

    it('Should have a login method',() => { 
     expect(service.login()).toBeTruthy(); 
    }); 

}); 

當我運行測試我得到這個錯誤:(順便說一句,我使用的角度cli)

Error: Cannot resolve all parameters for 'Router'(RouteRegistry, Router, ?, Router). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'Router' is decorated with Injectable.

我在這裏錯了嗎?

回答

1

經過大量的和周圍的搜索後,我發現我注射了錯誤的供應商。

基於這個偉大article我設法改變我的服務,這對解決我的問題:

import { Http } from '@angular/http'; 
import { provide } from '@angular/core'; 
import { SpyLocation } from '@angular/common/testing'; 
import { AuthHttp, JwtHelper } from 'angular2-jwt'; 
import { 
    Router, RootRouter, RouteRegistry, ROUTER_PRIMARY_COMPONENT 
} from '@angular/router-deprecated'; 
import { 
    beforeEach, beforeEachProviders, 
    describe, xdescribe, 
    expect, it, xit, 
    async, inject 
} from '@angular/core/testing'; 
import { UserService } from './user.service'; 

describe('User Service',() => { 

    let service = UserService.prototype; 

    beforeEachProviders(() => [ 
    RouteRegistry, 
    provide(Location, {useClass: SpyLocation}), 
    provide(ROUTER_PRIMARY_COMPONENT, {useValue: UserService}), 
    provide(Router, {useClass: RootRouter}), 
    AuthHttp, 
    Http, 
    UserService 
    ]); 

    it('Should have a login method',() => { 
     expect(service.login).toBeTruthy(); 
    }); 

});