假设有一个简单的服务 YourService:
// your.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class YourService {
getData(): string {
return 'Hello from YourService!';
}
getAsyncData(): Promise<string> {
return new Promise(resolve => {
setTimeout(() => {
resolve('Async data from YourService!');
}, 1000);
});
}
}
然后,可以使用 Jasmine 进行测试,通常包括以下步骤:
1. 导入测试模块和服务:
import { TestBed } from '@angular/core/testing';
import { YourService } from './your.service';
2. 配置 TestBed 并创建服务实例:
describe('YourService', () => {
let service: YourService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [YourService],
});
service = TestBed.inject(YourService);
});
// ...
});
3. 编写测试用例:
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should return data synchronously', () => {
const result = service.getData();
expect(result).toBe('Hello from YourService!');
});
it('should return data asynchronously', (done: DoneFn) => {
service.getAsyncData().then(result => {
expect(result).toBe('Async data from YourService!');
done();
});
});
这是一个基本的服务测试的示例。在实际项目中,你可能会遇到更复杂的场景,例如需要模拟依赖、使用测试工具库如 jasmine-marbles 处理 RxJS 流,等等。
如果服务中依赖了其他服务,你可以使用 TestBed.configureTestingModule 的 providers 属性来提供这些服务的测试替代品。还可以使用 spyOn 来监视服务方法的调用,以确保它们被正确调用。
import { TestBed } from '@angular/core/testing';
import { YourService } from './your.service';
import { AnotherService } from './another.service';
describe('YourService', () => {
let service: YourService;
let anotherServiceSpy: jasmine.SpyObj<AnotherService>;
beforeEach(() => {
const spy = jasmine.createSpyObj('AnotherService', ['someMethod']);
TestBed.configureTestingModule({
providers: [
YourService,
{ provide: AnotherService, useValue: spy },
],
});
service = TestBed.inject(YourService);
anotherServiceSpy = TestBed.inject(AnotherService) as jasmine.SpyObj<AnotherService>;
});
it('should call another service method', () => {
service.someMethodThatCallsAnotherService();
expect(anotherServiceSpy.someMethod).toHaveBeenCalled();
});
});
以上示例是一个入门级的 Angular 服务测试。在实际应用中,你可能需要深入学习 Angular 的测试工具和技术,以更全面地覆盖你的服务。
转载请注明出处:http://www.pingtaimeng.com/article/detail/4957/Angular