Typescript check for type with Jest

Assume there is an interface defined as follows:

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

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

}

To test the validity and type of the returned data, the following test is written:

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, an error occurs:

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

How can the test be modified to verify that the received data is valid and of the correct type?

Answer №1

When searching for a call type, remember that the .toBeInstanceOf(Class) method requires a JavaScript class constructor as a parameter, not a TS type.

It is important to have TSC verify the data type you are receiving at compile time. Any code written within test suites and test cases will be executed at runtime, meaning that .toBeInstanceOf(Class) is a check performed at runtime, not during compilation.

During runtime, consider utilizing expect.objectContaining(object) which matches any received object that recursively aligns with the expected properties.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for transferring data from a service to a method within a component

I have a service that successfully shares data between 2 components. However, I now need to trigger a method in component A when an event occurs on the service (and pass a value to that component). Can someone guide me on how to achieve this? I have seen ...

AngularJS textbox validation for numbers and required in repeating mode ensures that the user input is a

For more information, please visit the following link: https://plnkr.co/edit/9HbLMBUw0Q6mj7oyCahP?p=preview var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope) { $scope.NDCarray = [{val: '' ...

Utilizing Angular's $locationProvider in conjunction with ASP.NET MVC routing

Currently, I am managing routing in ASP.NET MVC using the RouteCollection class. However, my front end is built with Angular and there are instances where I need to update the URL using Angular's $location service while also supporting HTML5. To achie ...

An element in CSS that has a position of fixed and a width of 100% surpasses the dimensions of its

My element has the CSS properties position:fixed and width:100%, causing it to be larger than its parent elements. Despite the complexity of my code, I have attempted to simplify it for better understanding. Below, you can see that the green box exceeds ...

Using dangerouslySetInnerHTML in React within a Fragment

In my current project, I have a specific requirement where I need to format text in React and also include HTML rendering. Here's an example of what I'm trying to accomplish: import React, {Fragment} from "react"; import {renderToString} from " ...

Unlocking the potential of Object[value] in JavaScript/jQuery: A guide to extracting its value

I have a table named 'mytable' with the following structure: <tr> <td><input type="checkbox" name="check[]" value="11"></td> <td>11</td> <td>2014-11-06 18:49:26</td> < ...

How to stop Mouseenter event from bubbling up in an unordered list of hyperlinks using Vue 3

I've experimented with various methods to prevent event bubbling on the mouseenter event, but I'm still encountering an issue. When I hover over a link, the event is triggered for all the links as if they were all being hovered over simultaneousl ...

I am looking to retrieve information from mongodb and then transform it into a JSON object using node.js. Can you guide

I am on a mission to retrieve data from a MongoDB database and transform it into a JSON object in Node.js. The goal is to be able to easily manipulate this data as if it were a simple JSON object. Here's the current code snippet I'm working with: ...

Using Rails' link_to method within Bootstrap modals

I'm trying to implement a voting system where users can vote on different items displayed in a Bootstrap modal. Each item is listed as a button on the index page, and when clicked, it opens up the modal for voting. However, I'm facing challenges ...

Toggle the visibility of a div element and smoothly scroll to it on the page

Upon clicking the form, my goal is to show or hide it and scroll down to view the form. The current code I have in place seems to work after the first click. However, on the initial click, it shows the form but fails to scroll down. Any insights on what I ...

The drop-down menu remains visible even after clicking outside of it

I've written a script that works when clicked, but it doesn't hide when clicked outside of it. $(document).ready(function() { //Translate(); //caling Language Translater function $("#translate_image").attr('href', base_url) ...

Utilizing requirejs or grunt for concatenation and minification greatly enhances the performance of AngularJS implementations

I'm facing a dilemma with my Angular app. I have several JS files included in the index.html file, and when the app loads, all these files are downloaded before the app is ready. <html> ... <script src="scripts/controllers/loginController.js ...

Traversing a series of HTML form elements in order to extract their current values and store them in an object

Suppose we have an HTML structure like this: <nav data-filters class=""> <input type="radio" name="type" value="company" checked>Company <input type="radio" name="type" value="product">Product <input type=" ...

AngularJS - Setting an initial delay for ng-bind

We have a span element with the following attributes: <span role="link" ng-show="showLink()" ng-bind="textLink"></span> (Just an fyi: we implemented a fade-in, fade-out animation for this link, hence the use of ng-show instead of ng-if) The ...

A guide on organizing similar elements within an array using Angular

Could you assist me in grouping duplicate elements into separate arrays of objects? For example: array = [{key: 1}, {key: 5}, {key: 1}, {key: 3}, {key: 5}, {key: 1}, {key: 3}, {key: 2}, {key: 1}, {key: 4}]; Expected output: newArrayObj = {[{key: 1}, {key ...

What is the proper way to incorporate ts-nameof in the gulp build process and encounter the error message: 'getCustomTransformers' is a compiler option that is not recognized

Utilizing ts-nameof in my TypeScript files, similar to this example in a .ts file: import 'ts-nameof'; export class MyTsNameOfTest { public testTsNameOf() { const nameString = nameof(console.log); } } My Gulp build task setup - followi ...

Update data dynamically on a div element using AngularJS controller and ng-repeat

I am currently navigating my way through Angular JS and expanding my knowledge on it. I have a div set up to load data from a JSON file upon startup using a controller with the following code, but now I am looking to refresh it whenever the JSON object cha ...

How can I invoke a function within a directive-generated HTML element's scope?

I created a custom directive that utilizes element.html() to set the HTML content. Within this HTML code, I would like to be able to invoke functions from the scope where the directive is being used. Here's an example: app.directive('myDirective ...

Converting javascript html object lowercase

Is there a way to dynamically adjust the height of specific letters in my label? Right now, I am overriding the text for the elements: let element = document.getElementById('xxx') element.textContent = 'Label' I attempted using <sup ...

Why does my POST request result in [object Object] being returned?

I am just starting to learn AngularJS and I am unsure if my POST request is functioning correctly. After making the request, I am receiving an [object Object] response. What does this error indicate? Could it be related to an issue with the form? //Acti ...