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

ric*_*200 7 javascript node.js sinon sinon-chai axios

似乎有很多不同的方法可以做到这一点,但我试图只使用 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?

});
Run Code Online (Sandbox Code Playgroud)

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

小智 5

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

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

在您的示例中,res是由 sinon 创建的函数。该函数不会有 property data

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

const res = {
  send: sinon.spy()
}
Run Code Online (Sandbox Code Playgroud)

这给你一个res对象,其中有一个带有 key 的间谍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

});
Run Code Online (Sandbox Code Playgroud)