【问题标题】:Mock custom service in angular2 during unit test在单元测试期间在 angular2 中模拟自定义服务
【发布时间】:2017-03-12 04:05:37
【问题描述】:

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

组件:

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

服务:

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

组件单元测试:

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

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",
    ...
  }
}

当我执行 'karma start' 时出现此错误

错误:./PoniesComponent 类 PoniesComponent_Host 中的错误 - 内联模板:0:0 原因是:没有 Http 提供程序!在 config/karma-test-shim.js 中

看起来 karma 使用 PonyService 而不是将其嘲笑为 MockPonyService,尽管有这行:providers: [{provide: PonyService, useClass: MockPonyService}]。

问题:我应该如何模拟服务?

【问题讨论】:

    标签: unit-testing angular mocking karma-jasmine


    【解决方案1】:

    因为这个

    @Component({
      providers: [PonyService]  <======
    })
    

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

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

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

    【讨论】:

    • +1。但是由于服务是完全无状态的,它应该是一个单例并且在模块提供者而不是组件提供者中声明。
    【解决方案2】:

    另一种有效的方法是使用令牌并依赖接口而不是基类或具体类,像我这样的恐龙喜欢这样做(DIP、DI 和其他 SOLID Blablahs)。并允许您的组件注入其依赖项,而不是在您自己的组件中自己提供它。

    你的组件不会有任何提供者,它会在 angular 的 magic 依赖注入期间在其构造函数中接收对象作为接口。请参阅构造函数中使用的@inject,并将提供程序中的“提供”值视为文本而不是类。

    因此,您的组件将更改为:

    constructor(@Inject('PonyServiceInterface') private ponyService: IPonyService) {
       this.ponies = this.ponyService.getPonies(2); }
    

    在您的@Component 部分中,您将删除提供程序并将其添加到父组件,例如“app.component.ts”。在那里你会添加一个令牌:

    providers: [{provide: 'PonyServiceInterface', useClass: PonyService}]
    

    您的单元测试组件(类似于 app.component.ts)将具有: 提供者:[{provide: 'PonyServiceInterface', useClass: MockPonyService}]

    所以你的组件并不关心服务做什么,它只是使用接口,通过父组件(app.component.ts 或你的单元测试组件)注入。

    仅供参考:@inject 方法的使用不是很广泛,而且在某些时候,由于底层 javascript 的工作方式,看起来 Angular 研究员更喜欢基类而不是接口。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-14
      • 2012-11-15
      • 2023-04-01
      • 1970-01-01
      • 2020-03-22
      相关资源
      最近更新 更多