[英]Jest typescript check for type
假設我有以下界面:
export interface CMSData {
id: number;
url: string;
htmlTag: string;
importJSComponent: string;
componentData: ComponentAttribute[];
}
然后我有一個返回此對象類型array
的method
:
public async GetContent(url: string): Promise<CMSData[]>{
const response = await super.get<ICMSContentData[]>(url, {});
try {
if (response?.parsedBody) {
return this.ProcessResponse(response.parsedBody);
} else {
this.handleHTTPError(new Error("Error"));
return [];
}
} catch (e) {
this.handleHTTPError(e);
return [];
}
}
然后我想測試是否是這種情況,所以我編寫了以下test
:
import {ContentIOService} from "..";
import {CMSData} from "../IOServices/ContentIOService";
require('es6-promise').polyfill();
require('isomorphic-fetch');
test('Get Content', async () => {
const service = ContentIOService.getInstance();
const data = await service.GetContent("https://1c7207fb14fd3b428c70cc406f0c27d9.m.pipedream.net");
console.log(data)
expect(data).toBeInstanceOf(CMSData[]);
});
但是在這里我收到以下錯誤:
'CMSData' 僅指一種類型,但在此處用作值。
那么我如何測試我返回的數據是否有效且類型正確?
.toBeInstanceOf(Class)方法接受一個必須是一個類的參數。
您應該讓 TSC 在編譯時檢查您是否收到正確類型的數據。
在運行時,您可能希望使用expect.objectContaining(object)匹配任何遞歸匹配預期屬性的接收對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.