【发布时间】:2021-01-09 19:13:11
【问题描述】:
假设我有以下界面:
export interface CMSData {
id: number;
url: string;
htmlTag: string;
importJSComponent: string;
componentData: ComponentAttribute[];
}
然后我有一个method,它返回这个对象类型的array:
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' 仅指一种类型,但在这里用作值。
那么我如何测试我返回的数据是否有效且类型正确?
【问题讨论】:
-
这是正确的,因为你不能在这里使用
CMSData作为类的实例。它只是一种不会包含在捆绑代码中的类型。 -
instanceof是一个 JavaScript 二元运算符,它接受两个操作数,这两个操作数都是 值。这听起来像 Java 的instanceof,但它甚至不是类似的。阅读为value instanceof anotherValue。 -
你不需要测试,这就是打字稿的用途。如果返回类型不同,打字稿会在编码时通知您。
标签: javascript typescript unit-testing jestjs