Jasmine / Karma测试服务与params

时间:2017-07-10 10:44:12

标签: angular karma-jasmine

我想用Jasmine& amp; Karma与TestBed或SpyOn的服务依赖关系。但我没有在Angular网站上找到任何关于我如何做到的例子:https://angular.io/guide/testing

我该怎么做?

2 个答案:

答案 0 :(得分:0)

这是关于如何开始测试服务的最小示例。在大多数情况下,您不需要使用TestBed,因此我将其排除在最小单元测试示例之外:

Abc服务:

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

@Injectable()
export class AbcService {

  constructor(private otherService) {
  }

  add(x: number, y: number) {
    return x + y;
  }

  submit(x) {
    this.otherService.submit(x);
  }

}

Abc服务规范文件:

import { AbcService } from './abc';


describe('AbcService', () => {

  it('should add 1 + 2', () => {
    // Arrange
    const sut = new AbcService(null);

    // Act
    const result = sut.add(1, 2);

    // Assert
    expect(result).toEqual(3);
  });

  it('should dispatch SET_INTERACTION when setAnswer is run', () => {

    // Arrange
    const mockOtherService = jasmine.createSpyObj('mockOtherService', ['submit']);
    const sut = new AbcService(mockOtherService);

    // Act
    sut.submit(10);

    // Assert
    expect(mockOtherService.submit).toHaveBeenCalledWith(10);
  });
});

答案 1 :(得分:0)

describe('Test Service', () => {
    let yourCurrentService: YouCurrentService;
    let yourServiceDependencyService : YourServiceDependencyService;

    beforeEach(() => {

      let injector = ReflectiveInjector.resolveAndCreate([
        YouCurrentService,
        YourServiceDependencyService
      ]);
      yourCurrentService = injector.get(YourServiceDependencyService);
      yourCurrentService = injector.get(YouCurrentService);
    });

    it('test', () => {

    });  
});