【问题标题】:How do I mock an async function that makes network request using axios?如何模拟使用 axios 发出网络请求的异步函数?
【发布时间】:2021-01-30 03:05:34
【问题描述】:

我想对下面的函数进行单元测试,该函数在我的 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
  }
}

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

【问题讨论】:

    标签: node.js unit-testing mocha.js chai sinon


    【解决方案1】:

    为了存根axios 函数,您需要一个名为proxyquire 的额外包。欲了解更多信息,请参阅How to use Link Seams with 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 };
    

    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',
          },
        });
      });
    });
    

    单元测试结果:

      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 |                   
    ----------|---------|----------|---------|---------|-------------------
    

    【讨论】:

      猜你喜欢
      • 2021-06-10
      • 2018-02-18
      • 1970-01-01
      • 2020-10-26
      • 2020-03-06
      • 2020-12-27
      • 1970-01-01
      • 2022-11-10
      • 2018-08-14
      相关资源
      最近更新 更多