【问题标题】:How to mock an axios request using sinon modules如何使用 sinon 模块模拟 axios 请求
【发布时间】:2019-11-14 18:54:26
【问题描述】:

似乎有很多不同的方法可以做到这一点,但我试图只使用 sinon、sinon-test、chai/mocha、axios、httpmock 模块。我无法成功模拟使用 axios 进行的 GET 调用。我希望能够模拟来自该 axios 调用的响应,因此单元测试实际上不必发出外部 API 请求。

我已尝试通过创建沙箱来设置基本单元测试,并使用 sinon 存根设置 GET 调用并指定预期响应。我对 JavaScript 和 NodeJS 不熟悉。

// Main class (filename: info.js)

function GetInfo(req, res) {
    axios.get(<url>).then(z => res.send(z.data));
}

// Test class (filename: info.test.js)

it ("should return info", () => {
    const expectedResponse = "hello!";
    const res = sinon.spy();
    const aStub = sinon.stub(axios, "get").resolves(Promise.resolve(expectedResponse));

    const req = httpMock.createRequest({method:"get", url:"/GetInfo"});

    info.GetInfo(req, res);

    // At this point, I need to evaluate the response received (which should be expectedResponse)
    assert(res.data, expectedResponse); // data is undefined, res.status is also undefined

    // How do I read the response received?

});

我需要知道如何读取应该发回的响应(如果它首先被 sinon 捕获)。

【问题讨论】:

    标签: javascript node.js axios sinon sinon-chai


    【解决方案1】:

    我假设您要检查的响应是将 z.data 传递给 res.send(z.data)

    我认为您的 Sinon Spy 设置不正确。

    在您的示例中,res 是由 sinon 创建的函数。此函数将没有属性data

    你可能想创建一个像这样的间谍:

    const res = {
      send: sinon.spy()
    }
    

    这会给你一个res 对象,它有一个带有密钥send 的间谍。然后您可以对用于调用res.send的参数进行断言

    it ("should return info", () => {
        const expectedResponse = "hello!";
        const res = {
          send: sinon.spy()
        };
        const aStub = sinon.stub(axios, "get").resolves(Promise.resolve(expectedResponse));
    
        const req = httpMock.createRequest({method:"get", url:"/GetInfo"});
    
        info.GetInfo(req, res);
    
        // At this point, I need to evaluate the response received (which should be expectedResponse)
        assert(res.send.calledWith(expectedResponse)); // data is undefined, res.status is also undefined
    
    });
    

    【讨论】:

    • 感谢您的回复。出于某种原因,针对 res.send 的断言对我来说失败了。 Res.send 根本没有被调用,我想验证一下 calledOnce = true。
    【解决方案2】:

    不知道这是否有帮助,但您可能没有得到正确的响应,因为 resolves 是一个带有承诺包装的返回。

    因此,通过使用 resolves 并在其中使用 Promise.resolve,您实际上是在 Promise 中返回 Promise 包装。

    也许您可以尝试将代码更改为以下代码。

    const aStub = sinon.stub(axios, "get").resolves(Promise.resolve(expectedResponse));
    

    const aStub = sinon.stub(axios, "get").resolves(expectedResponse);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-15
      • 1970-01-01
      • 2018-06-15
      • 2016-11-27
      • 1970-01-01
      • 2020-07-18
      • 2021-09-22
      • 2019-05-06
      相关资源
      最近更新 更多