简体   繁体   中英

Jest testing Get request

I am building an api with a GET request on /api/flights/ I get an array of Flights. All flights have same properties. I want to check if flights list in my response.body equals an array of the same type = Flight. Is there a way to do that in Jest?

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

    //Here i want to check if response.body equals an array of Flight type
});

my response.body:

{
"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;

I guess you would like to test so an item in the flights array has a specific set of keys? If this is true, then something like this would work:

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

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