Exploring the effectiveness of Jest for testing HTTP GET requests

I am currently developing an API that uses a GET request on /api/flights/ to retrieve an array of Flights. All flights in the array have the same properties. I am looking for a way to verify if the flights list in my response.body matches an array of the same type, Flight. Is there a method in Jest to achieve this?

test('Show flight', async () => {
    const response = await supertest(app.express)
        .get('/api/flights/')
        .expect(200);

    //Here I want to validate if the response.body matches an array of Flight type
});

This is what my response.body looks like:

{
"flights": [
    {
        "_id": "6300bee627fff32a054f5355",
        "name": "Kiyv Madrid",
        "from": "Kiyv",
        "destination": "Madrid",
        "transplants": [],
        "departureDate": "20.08.2022-09:30",
        "arrivalDate": "21.08.2022-01:00",
        "seatsCount": 150,
        "createdAt": "2022-08-20T11:00:54.844Z",
        "updatedAt": "2022-08-20T11:00:54.844Z",
        "__v": 0
    },
    {
        "_id": "6300bf0127fff32a054f5358",
        "name": "Kyiv Barcelona",
        "from": "Kyiv",
        "destination": "Barcelona",
        "transplants": [],
        "departureDate": "20.08.2022-09:30",
        "arrivalDate": "21.08.2022-01:00",
        "seatsCount": 150,
        "createdAt": "2022-08-20T11:01:21.853Z",
        "updatedAt": "2022-08-20T12:45:42.596Z",
        "__v": 0
    },
    {
        "_id": "6300bf2a1df953f67f0e79b5",
        "name": "Kyiv Madrid",
        "from": "Kyiv",
        "destination": "Madrid",
        "transplants": [],
        "departureDate": "20.08.2022-09:30",
        "arrivalDate": "21.08.2022-01:00",
        "seatsCount": 150,
        "createdAt": "2022-08-20T11:02:02.154Z",
        "updatedAt": "2022-08-20T11:02:02.154Z",
        "__v": 0
    }
  ]
}

flight.test.interface.ts

interface Flight {
    _id: string;
    name: string;
    from: string;
    destination: string;
    transplants: string;
    departureDate: string;
    arrivalDate: string;
    seatsCount: number;
    __v: number;
}

export default Flight;

Answer №1

If you're looking to verify that an item in the flights array contains a specific set of keys, you can achieve this with the following code snippet:

const flightData = response.body.flights
const requiredKeys = [
    "_id",
    "name",
    "from",
    "destination",
    "transplants",
    "departureDate",
    "arrivalDate",
    "seatsCount",
    "createdAt",
    "updatedAt",
    "__v"
]
expect(Object.keys(flightData[0]).sort()).toEqual(requiredKeys.sort())

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

The Server Components render encountered a glitch

Screenshot of the errorI am encountering a strange error only in the production environment. The lack of additional information leads me to believe it may be due to security measures put in place for production. Unfortunately, I have been unable to repli ...

Instead of automatically playing, Youtube videos either remain idle or display suggested videos

I am trying to play a specific moment of an embedded Youtube video using some javascript code. At the specified time, I execute the following code: document.getElementById("video").src= "https://www.youtube.com/embed/...?autoplay=1&start=212"; where ...

Ways to utilize a React custom hook that returns a value within the useEffect hook?

I'm dealing with a custom hook that returns a value based on the parameters it receives. In order to update this value dynamically, I attempted to use useEffect but encountered issues as the hook cannot be called within it. How can I work around this ...

Enhance the deserialization process in passport for node.js by including additional properties beyond just req.user

In Passport, the user object fetched from the database is assigned to req.user in its .deserializeUser function. I'm curious if it's possible to also retrieve other data such as req.cart or req.inventory that are associated with the same user bu ...

Issue with VueJs not triggering a re-render when a new element is added to an array

In my code, I have implemented a watcher to monitor the dropdown value. If the value is equal to "select", a new array named "option" is created with one element. There is a button that allows adding a value to the array when the dropdown value is "select" ...

error loading foursquare request

Hello everyone, I'm encountering a minor issue while attempting to access the foursquare api in order to gather information about a specific restaurant that I've entered into the search bar. Cross origin requests are only supported for protocol ...

Is it possible that activating the alert() function within a Node.js script could cause the server to freeze completely?

Given that Node.js operates on a single thread, is there a risk of freezing the entire server by calling functions like alert(), which typically wait for user input? Does Node.js have mechanisms in place to prevent such issues? ...

The JavaScript function is not functioning properly, whereas another function is working as intended

I have created a HTML form with 2 buttons and a table. Each row in the table consists of a checkbox and 2 text fields. The buttons allow users to add and remove rows from the table. The remove button only applies to rows where their checkbox is checked. T ...

Having trouble accessing the POST RESPONSE json in ReactJS and NodeJS

I have set up my own API server that is connected to a MySQL database. Whenever I send a request to the server, everything seems fine. I can see the input from the browser and the output from the database in the console. However, I am unable to see any new ...

When calling EntityManager.save(), any fields that are not provided will be saved as null values

Currently, I am using @nestjs/typeorm": "^8.0.2 in conjunction with Postgres and encountering an unusual issue that seems like unexpected behavior: When attempting to save a partial entity, the fields I specify are saved correctly, but the resul ...

The compiler throwing an error claiming that the indexOf method is not a valid

Currently, I am working on a simple form that collects user input and aims to validate the email field by checking for the presence of "@" and "." symbols. However, every time I attempt to run it, an error message stating that indexOf is not a function p ...

Error occurs when ng-include is used within a ui-view

When implementing Angular.js in my application, I encountered an error when using ng-include within ui-view. The error message reads: Error: e is null .after/<@http://localhost/vb-asli/js/angular.min.js:152:228 r@http://localhost/vb-asli/js/angular.min ...

Guide on leveraging npm start to compile ES6 React components and Foundation Sass

Following a tutorial on setting up a React project, everything seemed to be working perfectly after installation. However, I now need to incorporate Foundation as the front-end library for a website. The issue arises because the tutorial's server.js ...

Ensure Website Accessibility by Implementing Minimum Resolution Requirements

Is it possible to create a website that only opens on screens with a resolution of at least 1024 x 768, and displays an error message on unsupported resolutions? I've tried using JavaScript to achieve this, but haven't had any success. Any assis ...

"Obtaining table row values by clicking a button in Angularjs - a step-by-step guide

I am seeking guidance on extracting the table row values of the selected row in the provided Plunkr. When a row is selected using the checkbox in the table and the update button is clicked, I require the row ID, name, and values. You can access the Plunk ...

Should I consider extracting the shared parts of similar pages into components when styling in React, or is it better to just share style sheets?

My website has two pages - a character page and a staff page, both of which look very similar. However, due to different data structures and minor differences, I am unable to separate the logic with view and reuse it across both pages. This made me conside ...

AngularJS Assessing an Attribute directive following an Element directive

Currently, I am utilizing an angular plugin that can be found at the following link: https://github.com/angular-slider/angularjs-slider The objective is to customize the "legends" produced by the directive. In order to achieve this customization, the dire ...

Encountered a type error during project compilation: "Type '(e: ChangeEvent<{ value: string[] | unknown; }>) => void' error occurred."

I recently started working with react and I'm facing an issue with a CustomMultiSelect component in my project. When I try to call events in another component, I encounter the following error during the project build: ERROR: [BUILD] Failed to compile ...

I'm looking to configure @types for a third-party React JavaScript module in order to use it with TypeScript and bundle it with webpack. How can I accomplish this?

Imagine you have a third-party npm package called @foo that is all Javascript and has a module named bar. Within your TypeScript .tsx file, you want to use the React component @foo/bar/X. However, when you attempt to import X from '@foo/bar/X', y ...

What is the method for configuring HTTPS on node.js in Azure Websites to ensure secure connections?

While using Windows Azure Websites and wanting to enable SSL with the default *.azurewebsites.net certificate, I found that HTTPS works seamlessly without any extra configuration. However, HTTP is still accessible along with HTTPS for all destinations. How ...