我试图在ionic4应用程序中对我的一些代码进行单元测试,调用一个端点并将响应映射到一个对象,它还会添加一个抽头,以便我可以从dataservice中将this.faults作为可观察的返回。
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();
});
});
但是我收到错误消息无法读取未定义的属性“管道”,我是否需要从httpstub返回任何内容?
答案 0 :(得分:2)
这是针对您的服务编写单元测试的正确方法。
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()
来实现。我上面包含的代码是一种更好,更彻底的测试实现。