【发布时间】:2017-12-14 01:36:58
【问题描述】:
我想使用 Jasmine 和 Karma 测试使用 TestBed 或 SpyOn 的服务依赖项。但我在 Angular 网站上没有找到任何示例:https://angular.io/guide/testing
我该怎么做?
【问题讨论】:
标签: angular karma-jasmine
我想使用 Jasmine 和 Karma 测试使用 TestBed 或 SpyOn 的服务依赖项。但我在 Angular 网站上没有找到任何示例:https://angular.io/guide/testing
我该怎么做?
【问题讨论】:
标签: angular karma-jasmine
这是一个关于如何开始使用测试服务的最小示例。在大多数情况下,您不需要使用 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);
});
});
【讨论】:
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', () => {
});
});
【讨论】: