提问者:小点点

如何使用sinon模块模拟axios请求


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

我尝试过通过创建沙箱来建立一个基本的单元测试,并使用sinon stub来建立一个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捕获)。


共2个答案

匿名用户

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

我不认为你的Sinon间谍设置正确。

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

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

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

这为您提供了一个res对象,其中包含带有密钥发送的间谍。然后,您可以对用于调用 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

});

匿名用户

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

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

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

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

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