Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

test responsebody with Jest and supertest

I have a simple express http server that returns "Hello worl" when issuing a get to /

And I have the following test:

import request from 'supertest';
import app from '../app/app';

test('test http server', async () => {
  const res = await request(app).get('/')
  expect(res.body).toEqual('Hello world');
});

The test fails like this:

● test http server
expect(received).toEqual(expected)
Expected: "Hello world"
Received: {}
   7 |   const res = await request(app).get('/')
   8 | 
>  9 |   expect(res.body).toEqual('Hello world');

How can I get the response.body as text to check it?

like image 369
opensas Avatar asked Oct 17 '22 05:10

opensas


1 Answers

it seems like then returning only text (no json) you have yo use res.text, like this:

test('test http server', async () => {
  const res: request.Response = await request(app).get('/')

  expect(res.type).toEqual('text/html');
  expect(res.text).toEqual('Hello world');
});

On the other hand, when testing an endpoint that returns json I can do like this:

test('test valid_cuit with a valid case', async () => {
  const cuit: string = '20-24963205-9'
  const res: request.Response = await request(app).get(`/api/valid_cuit/${ cuit }`)

  expect(res.type).toEqual('application/json')
  expect(res.body.cuit).toEqual(cuit)
  expect(res.body.isValid).toBe(true)
});
like image 102
opensas Avatar answered Oct 21 '22 03:10

opensas