我试图在离子应用程序代码中对我的代码进行单元测试,调用端点并将响应映射到对象,它还添加了一个点击,这样我就可以将this.faults作为我的dataservice中的一个observable返回。
fetchFaults(): Observable<Fault[]>
{
return this.http.get<{data: Fault[]}>('https://server/api/faults')
.pipe(tap((data) => this.faults = data.data) // cache
, map((data) => data.data)); // return just Fault[] from data.data to the subscriber
}
我正试图测试
describe('fetchFaults', () => {
it('makes expected calls', () => {
const httpClientStub: HttpClient = TestBed.get(HttpClient);
spyOn(httpClientStub, 'get');
service.fetchFaults();
expect(httpClientStub.get).toHaveBeenCalled();
});
});
但是我收到错误无法读取属性'pipe'的undefined我需要从httpstub返回任何内容吗?
以下是针对您的服务编写单元测试的正确方法。
import { TestBed, fakeAsync, tick, getTestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { FaultService, Fault } from './fault.service';
describe('Program Service Tests', () => {
let injector: TestBed;
let service: FaultService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
FaultService
]
});
injector = getTestBed();
service = injector.get(FaultService);
httpMock = injector.get(HttpTestingController);
});
afterEach(() => {
httpMock.verify();
});
it('should get the faults', fakeAsync(() => {
const results = {data: []};
service.fetchFaults().subscribe(_ => expect(results.data).toBe(_));
const req = httpMock.expectOne((request: HttpRequest<any>): boolean => {
expect(request.url).toEqual('https://server/api/faults');
expect(request.method).toBe('GET');
return true;
});
req.flush(results);
tick();
}));
});
您收到该错误的原因是您需要告诉间谍调用原始实现。你可以通过链接.and.callThrough()
来做到这一点。一个更好,更彻底的测试实现是我上面包含的代码。