我正在尝试在我的服务中对该功能进行单元测试,该服务首先执行POST请求,然后再执行GET。我正在使用switchMap来完成此操作,但是我遇到的问题是两个请求都没有被HttpTestingController匹配功能接收]
这是我要测试的服务功能:
save(cow: Cow): Observable<Object> {
return this.http.put<Cow>(`${this.cowUrl}/1`, cow, this.httpOptions)
.pipe(switchMap(_ => {
return this.getAllCows();
})
);
}
private getAllCows(): Observable<Cow[]> {
return this.http.get<Cow[]>(`${this.cowUrl}`).pipe(tap(data => {
this.cows = data;
}),
catchError(this.handleError<Cow[]>('getAllCows'))
);
}
这里是该功能的规格:
describe('CowService', () => {
let cowService: CowService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule
]
});
cowService = TestBed.get(CowService);
httpMock = TestBed.get(HttpTestingController);
});
afterEach(() => {
httpMock.verify();
});
describe('save', () => {
const cowList: Cow[] = [
{ id: '1', name: 'Cow' },
{ id: '2', name: 'Another Cow' }
];
it('Successfully saves cow and updates the list of cows', () => {
const cow: Cow = { id: null, name: 'Third Cow' };
cowService.save(cow).subscribe();
const reqs = httpMock.match(request => request.url = '/api/cows');
console.log(reqs); // shows only the POST request and not the GET
expect(reqs[0].request.url).toEqual('/api/cows');
expect(reqs[0].request.method).toEqual('POST');
expect(reqs[1].request.url).toEqual('/api/cows');
expect(reqs[1].request.method).toEqual('GET');
reqs[0].flush({});
reqs[1].flush(cowList);
});
});
});
执行此操作时,出现错误消息:
TypeError:无法读取未定义的属性“ flush”
尝试以下操作: