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

编程入门 行业动态 更新时间:2024-10-27 13:28:29
本文介绍了如何模拟使用 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 发出网络请求的异步函数?

本文发布于:2023-10-09 18:53:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1476496.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   网络   axios

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!