如何模拟使用 axios 发出网络请求的异步函数?

Ayu*_*jha 1 unit-testing mocha.js node.js sinon chai

我想对下面的函数进行单元测试,该函数在我的 node.js 服务器中使用 axios 调用端点。

const callValidateCookieApi = async (cookie) => {
  try {
    const config = {
      method: 'post',
      url: process.env.API_COOKIE_VALIDATION,
      headers: {
        Cookie: cookie
      }
    }
    return await axios(config)
  } catch (error) {
    console.log(error.message)
    return error
  }
}
Run Code Online (Sandbox Code Playgroud)

如何通过模拟函数内部的 axios 调用来编写单元测试用例?

sli*_*wp2 5

为了存根axios函数,您需要一个名为proxyquire的额外包。有关更多信息,请参阅如何在 CommonJS 中使用链接接缝

单元测试解决方案:

index.js

const axios = require('axios');

const callValidateCookieApi = async (cookie) => {
  try {
    const config = {
      method: 'post',
      url: process.env.API_COOKIE_VALIDATION,
      headers: {
        Cookie: cookie,
      },
    };
    return await axios(config);
  } catch (error) {
    console.log(error.message);
    return error;
  }
};

module.exports = { callValidateCookieApi };
Run Code Online (Sandbox Code Playgroud)

index.test.js

const proxyquire = require('proxyquire');
const sinon = require('sinon');
const { expect } = require('chai');

describe('64374809', () => {
  it('should pass', async () => {
    const axiosStub = sinon.stub().resolves('fake data');
    const { callValidateCookieApi } = proxyquire('./', {
      axios: axiosStub,
    });
    const actual = await callValidateCookieApi('sessionId');
    expect(actual).to.be.eql('fake data');
    sinon.assert.calledWithExactly(axiosStub, {
      method: 'post',
      url: undefined,
      headers: {
        Cookie: 'sessionId',
      },
    });
  });

  it('should handle error', async () => {
    const mErr = new Error('network');
    const axiosStub = sinon.stub().rejects(mErr);
    const { callValidateCookieApi } = proxyquire('./', {
      axios: axiosStub,
    });
    const actual = await callValidateCookieApi('sessionId');
    expect(actual).to.be.eql(mErr);
    sinon.assert.calledWithExactly(axiosStub, {
      method: 'post',
      url: undefined,
      headers: {
        Cookie: 'sessionId',
      },
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

单元测试结果:

  64374809
    ? should pass (84ms)
network
    ? should handle error


  2 passing (103ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.js |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Run Code Online (Sandbox Code Playgroud)