【发布时间】:2018-05-29 10:58:05
【问题描述】:
我对如何测试数据服务感到很困惑,有太多的可能性,而且让人不知所措。
我有这个简单的服务:
@Injectable()
export class DataService {
constructor(private _http: HttpClient) { }
getData<T>(path: string): Observable<T> {
return this._http.get<T>(path);
}
}
我想测试一下,调用getData<number> 实际上会返回number 的数据类型。
angular testing guide 令人沮丧地展示了几种方法(使用 testbed、使用 beforeEach、使用没有 testBed 的 jasmine),我已经尝试了所有这些方法,但都没有多大成功。
请问我该怎么做?到目前为止,我什至无法拨打getData。我希望能够模拟 Http,发出模拟返回值(如在 jasmine.spy.and.returnValue(mockData) 中)并验证 dataService 是否正常
我的data.service.spec.ts 中有这个:
describe('DataService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientModule
],
providers: [
DataService,
HttpClient
]
});
});
// This was auto generated, and works
it('should be created', inject([DataService], (service: DataService) => {
expect(service).toBeTruthy();
}));
// I added this, but doesn't work
describe('When getData() is called', () => {
it('should return an observable of type T', inject([DataService], (service: DataService) => {
service.getData<number>('mock-url')
.subscribe(data => {
expect(typeof(data)).toBe('number');
});
}));
});
});
当我说它不起作用时……第二个测试通过了!但它不应该。我可以看到真正的请求在开发控制台上发送到(无效的)url,并且错误如预期的那样,但测试刚刚通过......
所以我想,我的问题很简单,在 Angular 5 中,我该如何模拟我的后端服务并对其进行单元测试?
【问题讨论】:
标签: angular unit-testing