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

时间:2016-07-08 09:52:22

标签: unit-testing typescript angular angular-cli

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

我的服务如下:

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

});

当我运行测试时出现此错误:(顺便说一句,我正在使用angular-cli)

  

错误:无法解析'Router'(RouteRegistry,Router,?,Router)的所有参数。确保所有参数都使用Inject进行修饰或具有有效的类型注释,并且“Router”使用Injectable进行修饰。

我在这里错了吗?

1 个答案:

答案 0 :(得分: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();
  });

});