gpt4 book ai didi

javascript - 如何在 Angular 单元测试中创建 ArrayBuffer 变量,Jasmine/Karma

转载 作者:行者123 更新时间:2023-11-30 14:03:00 26 4
gpt4 key购买 nike

您好,我有一个从后端下载 excel 文件的功能

component.ts

 getExcelExport(resultsFilterRootObject: ResultsFilterRootObject) {
return this.http.post(urls.getExcelExportCPPMetrics , resultsFilterRootObject, {
responseType: 'arraybuffer',
observe: 'response'
})
.pipe(
tap(
data => {
const blob = new Blob([data.body], {type: 'application/vnd.ms-excel'});
const filename = 'vehicle-metrics-template.xls';
FileSaver.saveAs(blob, filename);
},
catchError(MetricsService.handleError)
)
);
}

component.spec.ts

  it('should download Excel ', () => {

// const expectedResult: ArrayBuffer = new ArrayBuffer(8); Tried this fails too
const expectedResult = new TextEncoder();
expectedResult.encode("This is a string converted to a Uint8Array");

httpClientSpy.post.and.returnValue(asyncData(expectedResult));

metricsService.getExcelExportCPPMetrics(resultsFilterRootObject).subscribe(
heroes => expect(heroes).toEqual(expectedResult, 'expected VehicleSalesResultRootObject'),
fail
);
expect(httpClientSpy.post.calls.count()).toBe(1, 'one call');
});

我一直收到错误错误 TS2345:'TextEncoder' 类型的参数不可分配给类型为 'Expected<HttpResponse<ArrayBuffer>>'. 的参数

Type 'TextEncoder' is missing the following properties from type 'ObjectContaining<HttpResponse<ArrayBuffer>>': jasmineMatches, jasmineToString

Basically if I can create a variable of type ArrayBuffer in the Unit Test this problem would be solved

对此有什么想法吗?

最佳答案

请注意 post带参数的方法 responseType: 'arraybuffer'observe: 'response'返回值 Observable<HttpResponse<ArrayBuffer>>这不是直接ArrayBuffer在那里提供:

post(url: string, body: any | null, options: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe: 'response';
params?: HttpParams | {
[param: string]: string | string[];
};
reportProgress?: boolean;
responseType: 'arraybuffer';
withCredentials?: boolean;
}): Observable<HttpResponse<ArrayBuffer>>;

你可以做的是返回 Observable使用具有您正在使用的属性的简单对象 - body :

  it('should download Excel ', () => {
const expectedResult: ArrayBuffer = new ArrayBuffer(8);
// httpClientSpy.post.and.returnValue(asyncData(expectedResult));
httpClientSpy.post.and.returnValue(of({body: expectedResult})); // Or that below one if "asyncData" return Observable

metricsService.getExcelExportCPPMetrics(resultsFilterRootObject).subscribe(
data => expect(data.body).toEqual(expectedResult, 'expected VehicleSalesResultRootObject'),
fail
);
expect(httpClientSpy.post.calls.count()).toBe(1, 'one call');
});

关于javascript - 如何在 Angular 单元测试中创建 ArrayBuffer 变量,Jasmine/Karma,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55976331/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com