【问题标题】:nodejs supertest express test prior to invoking external API调用外部 API 之前的 nodejs supertest 快速测试
【发布时间】:2022-01-01 21:16:57
【问题描述】:

不确定这是否可行,但我想在不调用外部 API POST 请求的情况下运行测试。

目前发生的情况是,我进行了一项测试,确认发送到我的服务器 API 的发布数据得到了正确处理,因为它需要在将其发送到外部 API 之前向 BODY 添加一些基本的附加信息,然后服务器再创建一个使用此修改后的 BODY 向外部 API 发出 POST 请求。

这一切都在下面的函数中完成。

createUser(req,res){
...
// schema validation,

// adding fields

// external server post request


}

是否可以让我的测试忽略外部 API 调用?

测试看起来像

    it('POST users --> 200 Successful Post', () => {
        return request(app).post('/api/users').send(........ my json .......)
        .expect('Content-Type', /json/)
        .expect(200)    
        .then((response) => {
            expect(response.body).toEqual(
                ......
            )
        })
    });

【问题讨论】:

    标签: node.js express axios


    【解决方案1】:

    您可以使用nock 拦截和模拟测试请求。

    在您的测试中,您可以像这样设置您的模拟对象:

    const nock = require("nock");
    
    const scope = nock("https://api.github.com")
        .get("/repos/atom/atom/license")
        .reply(200);
    

    它将拦截到/repos/atom/atom/license的HTTPS GET请求。

    How to Test Node.js Apps That Interact With External APIs

    【讨论】:

      猜你喜欢
      • 2014-09-02
      • 2019-10-01
      • 1970-01-01
      • 2020-02-15
      • 2013-12-10
      • 2020-08-21
      • 1970-01-01
      • 1970-01-01
      • 2012-10-01
      相关资源
      最近更新 更多