【问题标题】:Unable to mock external api using Nock无法使用 Nock 模拟外部 api
【发布时间】:2018-07-12 18:55:12
【问题描述】:

我有一个 Node.js 服务,它调用外部 API 以在向用户返回响应之前收集一些数据。我想模拟这个外部 API,以便测试我的服务,但不幸的是,我得到的响应没有内容(只有 200 的状态)。这是我的测试:

const nock = require('nock');
const expect = require('chai').expect;
const request = require('supertest');
const httpStatus = require('http-status');

var app = require('../index');

describe('Get Account Summary test', function () {

    it('Should return a clients account summary successfully', function (done) {

        nock('https://external.api')
            .post('/v3/restful-api-endpoint')
            .reply(200, {
                "status": 200,
                "message": "This is a mocked response"
            });

        request(app)
            .get('/api/account/summary/dummy-request-id')
            .expect(httpStatus.OK)
            .end(function(err, res) {
                expect(res.body.message).to.equal('This is a mocked response');
                done();
            });
    });
});

res.body 返回未定义。我不明白为什么。

【问题讨论】:

    标签: javascript node.js nock


    【解决方案1】:

    没有端点的来源,很难说,但问题很可能出在那儿。测试本身似乎没有太大问题。请务必等待来自外部 API 的响应(使用 Promise、async/await 或回调,因为这通常会造成混乱。

    【讨论】:

    • 所以我的服务使用 GET 动词,但我需要使用 POST 调用外部 API。这就是为什么我在外部 API 调用上有 POST。
    • 我的错,我错过了路线不同。在这种情况下,响应可以是任何内容,因为我们不知道端点代码中的内容。您可能也想发布它。
    • 对……这实际上是有道理的。因为我正在接受一个响应并将其转换为另一个响应。我需要弄清楚那里的转变
    • 是的!我会修改我的答案,如果您仍然无法正常工作,我想发布。专业提示:确保在响应之前等待来自外部 API 的响应,这是导致未定义值的常见原因。
    • 您帮助追踪了问题。欣赏。
    猜你喜欢
    • 2020-09-02
    • 2021-05-31
    • 2022-10-24
    • 2017-10-17
    • 1970-01-01
    • 2017-07-24
    • 1970-01-01
    • 1970-01-01
    • 2015-03-20
    相关资源
    最近更新 更多