如何模拟使用 axios 发出网络请求的异步函数? [英] How do I mock an async function that makes network request using axios?

查看:103
本文介绍了如何模拟使用 axios 发出网络请求的异步函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to unit test a function below that calls an endpoint using axios in my node.js server.

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 调用来编写单元测试用例?

How do I write unit test cases by mocking the axios call that is inside the function?

推荐答案

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

In order to stub axios function, you need an extra package named proxyquire. For more info, see 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 |                   
----------|---------|----------|---------|---------|-------------------

这篇关于如何模拟使用 axios 发出网络请求的异步函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆