在单元测试期间以angular2模拟定制服务

Evg*_*niy 16 unit-testing mocking karma-jasmine angular

我正在尝试为我的服务中使用的组件编写单元测试.组件和服务工作正常.

零件:

import {Component} from '@angular/core';
import {PonyService} from '../../services';
import {Pony} from "../../models/pony.model";
@Component({
  selector: 'el-ponies',
  templateUrl: 'ponies.component.html',
  providers: [PonyService]
})
export class PoniesComponent {
  ponies: Array<Pony>;
  constructor(private ponyService: PonyService) {
    this.ponies = this.ponyService.getPonies(2);
  }
  refreshPonies() {
    this.ponies = this.ponyService.getPonies(3);
  }
}
Run Code Online (Sandbox Code Playgroud)

服务:

import {Injectable} from "@angular/core";
import {Http} from "@angular/http";
import {Pony} from "../../models/pony.model";
@Injectable()
export class PonyService {
  constructor(private http: Http) {}
  getPonies(count: number): Array<Pony> {
    let toReturn: Array<Pony> = [];
    this.http.get('http://localhost:8080/js-backend/ponies')
    .subscribe(response => {
      response.json().forEach((tmp: Pony)=> { toReturn.push(tmp); });
      if (count && count % 2 === 0) { toReturn.splice(0, count); } 
      else { toReturn.splice(count); }
    });
    return toReturn;
  }}
Run Code Online (Sandbox Code Playgroud)

组件单元测试:

import {TestBed} from "@angular/core/testing";
import {PoniesComponent} from "./ponies.component";
import {PonyComponent} from "../pony/pony.component";
import {PonyService} from "../../services";
import {Pony} from "../../models/pony.model";
describe('Ponies component test', () => {
  let poniesComponent: PoniesComponent;
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [PoniesComponent, PonyComponent],
      providers: [{provide: PonyService, useClass: MockPonyService}]
    });
    poniesComponent = TestBed.createComponent(PoniesComponent).componentInstance;
  });
  it('should instantiate component', () => {
    expect(poniesComponent instanceof PoniesComponent).toBe(true, 'should create PoniesComponent');
  });
});

class MockPonyService {
  getPonies(count: number): Array<Pony> {
    let toReturn: Array<Pony> = [];
    if (count === 2) {
      toReturn.push(new Pony('Rainbow Dash', 'green'));
      toReturn.push(new Pony('Pinkie Pie', 'orange'));
    }
    if (count === 3) {
      toReturn.push(new Pony('Fluttershy', 'blue'));
      toReturn.push(new Pony('Rarity', 'purple'));
      toReturn.push(new Pony('Applejack', 'yellow'));
    }
    return toReturn;
  };
}
Run Code Online (Sandbox Code Playgroud)

package.json的一部分:

{
  ...
  "dependencies": {
    "@angular/core": "2.0.0",
    "@angular/http": "2.0.0",
    ...
  },
  "devDependencies": {
    "jasmine-core": "2.4.1",
    "karma": "1.2.0",
    "karma-jasmine": "1.0.2",
    "karma-phantomjs-launcher": "1.0.2",
    "phantomjs-prebuilt": "2.1.7",
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

当我执行'karma start'时,我得到了这个错误

错误:./PoniesComponent类中的错误PoniesComponent_Host - 内联模板:0:0引起:没有Http的提供者!在config/karma-test-shim.js中

看起来karma使用PonyService而不是嘲笑它MockPonyService,尽管这条线:providers: [{provide: PonyService, useClass: MockPonyService}].

问题:我应该如何嘲笑服务?

Pau*_*tha 22

正因为如此

@Component({
  providers: [PonyService]  <======
})
Run Code Online (Sandbox Code Playgroud)

这使得服务的范围限定为组件,这意味着Angular将为每个组件创建它,并且还意味着它取代在模块级别配置的任何全局提供者.这包括您在测试台中配置的模拟提供程序.

为了解决这个问题,Angular提供了TestBed.overrideComponent一种方法,它允许我们覆盖像@Component.providers和的东西@Component.template.

TestBed.configureTestingModule({
  declarations: [PoniesComponent, PonyComponent]
})
.overrideComponent(PoniesComponent, {
  set: {
    providers: [
      {provide: PonyService, useClass: MockPonyService}
    ]
  }
});
Run Code Online (Sandbox Code Playgroud)