用Jest和supertest测试响应体

问题描述 投票:0回答:1

我有一个简单的快速http服务器,当发出get /时返回“Hello world”

我有以下测试:

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');
});

测试失败如下:

● 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');

我怎样才能将response.body作为文本进行检查?

express jestjs supertest
1个回答
0
投票

它似乎只返回文本(没有json)你必须使用res.text,像这样:

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');
});

另一方面,当测试返回json的端点时,我可以这样做:

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)
});
© www.soinside.com 2019 - 2024. All rights reserved.