【问题标题】:test responsebody with Jest and supertest用 Jest 和 supertest 测试 responsebody
【发布时间】:2019-07-31 20:23:29
【问题描述】:

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

我有以下测试:

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】:

    看起来你只返回文本(没有 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)
    });
    

    【讨论】:

      猜你喜欢
      • 2021-08-15
      • 1970-01-01
      • 2021-10-21
      • 2020-09-14
      • 2021-11-28
      • 2019-02-11
      • 1970-01-01
      • 2021-07-21
      • 2020-07-03
      相关资源
      最近更新 更多