【问题标题】:How to test express GET request?如何测试快速 GET 请求?
【发布时间】:2021-08-03 20:23:11
【问题描述】:

我在ExpressJS 有一个端点,它返回一个元素数组,但只有这些元素的类型与请求查询参数中的类型相同,这里是代码,

端点返回这个数组:

[
    {
        "type":[1,2]
    }
]

GET 请求如下所示:

http://localhost:3000/api/types?type=1&type=2

如何测试这个端点?我需要检查我的函数是否从请求查询中返回 type 数组包含 type 的对象,我尝试这样:

describe('getTypes()', () => {
    it('It should return only objects contains 1 as a type', async () => {
        const res = await request(app)
            .get('/api/types?type=1')

        expect(res.statusCode).toEqual(200);
    })
})

但我现在不知道该怎么做,谁能告诉我如何测试它?

感谢您的帮助!

【问题讨论】:

  • 您可以从响应中获取正文并期望它是您期望的任何内容。说了这么多,不懂逻辑。 3 和 4 来自哪里?
  • 这只是示例,我删除了 3 和 4,我不知道响应是什么样的,所以我无法抓住它并期待它
  • 如果您不知道响应是什么样的,那么您似乎无法测试它,只能断言它存在并且状态码与您预期的一样。

标签: javascript express testing jestjs


【解决方案1】:

我建议使用supertest HTTP 断言库。

使用这个库,您可以按如下方式测试您的端点:

imprt request from 'supertest';

describe('getTypes', () => {
    it('should return only type 1 objects', (done) => {
        request(app)
            .get('/api/types?type=1')
            .expect(200)
            .then(response => {
              expect(response.body[0].type).toBe([1]);
              done();
             })
            .catch(err => done(err))
    });
});

【讨论】:

    猜你喜欢
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-24
    • 2018-09-15
    • 2012-06-17
    • 2019-02-01
    • 2021-10-12
    • 2021-04-25
    相关资源
    最近更新 更多