如何对包含路由器弃用版本的 Angular 2.0 服务进行单元测试?

How to Unit Test an Angular 2.0 service that includes router-deprecated version?

这有点令人困惑,因为我在 Angular 2.0 和 Router-deprecated 的文档中找不到任何相关内容(是的,我仍然必须在我的项目中使用它)。

我的服务是这样的:

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)
      );
    }

}

我的测试是这样的(暂时不关心 'it' 部分):

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();
  });

});

当我 运行 测试时出现此错误:(顺便说一句,我正在使用 angular-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.

我错了吗?

经过大量搜索后,我发现我错误地注入了提供程序。

基于这个 GREAT 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();
  });

});