Nea*_*sis 5 unit-testing blob httpresponse jestjs angular
我正在开发 Angular 9 应用程序,并且正在编写单元测试,这要归功于 jest。我的 Angular 服务调用 Spring API,该 API 返回 CSV 文件以供下载。我想进行单元测试,但无法模拟 HttpResponse。
* MyService.ts *
downloadCsv(id: string) {
return this.http.get('/api/ + id + `/csv/`,
{ responseType: 'blob' as 'json', observe: 'response' });
}
Run Code Online (Sandbox Code Playgroud)
* MyService.spec.ts *
it(`should call the GET API and return a csv file as result`, () => {
// GIVEN
const expectedData: Blob = new Blob(['a', 'b', 'c', 'd']);
// WHEN
let actualData = {};
service.downloadCsv('1').subscribe(data => {
actualData = data;
});
// THEN
backendMock.expectOne((req: HttpRequest<any>) => {
return req.url === `/api/` + '1' + `/csv/`
&& req.method === 'GET';
}, `GET data to ${'/api/'}`)
.flush(expectedData);
expect(actualData).toEqual(expectedData);
});
Run Code Online (Sandbox Code Playgroud)
即使我尝试将新的 HttpResponse 放入预期数据中,我也不知道如何构建包含 blob 的 HttpResponse (我没有找到太多示例,并且文档并没有真正帮助我:/(HttpResponse 文档) )
我正在等待的回复如下所示:
有人能帮我吗 ?
你可以做这样的事情来模拟响应
const fakeFile = (): File => {
const blob = new Blob([''], { type: 'text/html' });
return blob as File;
};
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助 :)
| 归档时间: |
|
| 查看次数: |
11655 次 |
| 最近记录: |