小编ric*_*200的帖子

如何使用 sinon 模块模拟 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, …
Run Code Online (Sandbox Code Playgroud)

javascript node.js sinon sinon-chai axios

7
推荐指数
1
解决办法
9997
查看次数

标签 统计

axios ×1

javascript ×1

node.js ×1

sinon ×1

sinon-chai ×1