简体   繁体   中英

Jest typescript check for type

lets say i have the following interface:

export interface CMSData {
    id: number;
    url: string;
    htmlTag: string;
    importJSComponent: string;
    componentData: ComponentAttribute[];
}

Then i have a method that returns an array of this object type:

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 [];
    }

}

Then i want to test that this is the case so i write the following 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[]);
});

However here i get the following error:

'CMSData' only refers to a type, but is being used as a value here.

So how can i test that the data i get back is valid and of the right type?

.toBeInstanceOf(Class) method accept a parameter which MUST BE a class.

You should let TSC check whether you receive the correct type of the data at compile time.

At runtime, you may want to use expect.objectContaining(object) matches any received object that recursively matches the expected properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM