如何将ts-mockito注入Angular 4组件测试

时间:2017-10-26 16:59:46

标签: angular unit-testing typescript

typemoq注入this question类似,如何将ts-mockito个对象注入角度TestBed.configureTestingModule()?我能找到的任何example ts-mockito测试都与角度无关。

考虑以下最简单的工作示例进行测试 - 它包含ProgressComponent,后端有一个ProgressService我们正在嘲笑。这项服务非常简单:

import { Injectable } from '@angular/core';

@Injectable()
export class ProgressService {
    private currentState: string = '1';

    constructor() {
    }

    setCurrentState(state: string) {
        this.currentState = state;
    }

    getCurrentState(){
        return this.currentState
    }

}

要在没有ts-mockito的情况下进行模拟,我们只需扩展该类。

import {ProgressService} from "../../../progress.service";

export class MockProgressService extends ProgressService{}

然后在测试ProgressComponent时,MockProgressService会传递给TestBed。

import {async, ComponentFixture, getTestBed, TestBed} from '@angular/core/testing'

import { ProgressComponent } from './progress.component'
import {ProgressService} from "../progress.service"
import {MockProgressService} from "../shared/services/progress/progress.mock";

describe('ProgressComponent', () => {
  let injector: TestBed
  let mockService: ProgressService
  let fixture: ComponentFixture<ProgressComponent>
  let component: ProgressComponent

  beforeEach(async() => {
    TestBed.configureTestingModule({
      declarations: [ ProgressComponent ],
      providers: [{provide: ProgressService, useClass: MockProgressService}]
    }).compileComponents()

    injector = getTestBed()
    fixture = TestBed.createComponent(ProgressComponent)
    component = fixture.componentInstance
    mockService = injector.get(ProgressService)

    fixture.detectChanges();
  });
});

角度测试框架通过TestBed引入依赖注入。 我们如何在角度测试设置中使用mockito?例如,如何将代码段injector.get(ProgressService)与ts-mockito模拟兼容?

1 个答案:

答案 0 :(得分:2)

如果提供者应该使用其他对象而不是类进行模拟,则应使用useValueuseFactory

对于Jasmine,它是:

providers: [{
  provide: ProgressService,
  useValue: jasmine.createSpyObj('ProgressService', [...])
}]

对于ts-mockito,它可以是:

progressServiceMock = mock(ProgressService);
...
providers: [{provide: ProgressService, useValue: instance(progressServiceMock)}]

虽然继承像class MockProgressService extends ProgressService这样的模拟类frim原始类通常没有好处。如果想要模拟一些方法,可以使用jasmine.spy(或当前测试框架具有的对应物)在实际类实例或类原型上进行模拟。当一个类不是在当前单元测试中测试的类时,模拟/存根所有方法而不是几个方法都有利于测试隔离。