2016-07-08 43 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(); 
    }); 

});