单元测试:如何在反应中模拟 axios? [英] Unit test: How to mock axios in react?
问题描述
我正在 getArticlesFromDatabase 中测试 axios.
好像我做错了,导致控制台显示以下消息:
<块引用>(node:36919) UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝 ID:5):这里是拒绝失败:
(节点:36919)弃用警告:不推荐使用未处理的承诺拒绝.在未来,未处理的承诺拒绝将终止带有非零退出代码的 Node.js 进程.
如何解决?
<小时>csrfData.js
从'axios'导入axios;var getArticlesFromDatabase = new Promise(function(resolve, reject) {axios.get('127.0.0.1:8000/api/articles/get-articles-list').then(response=>{resolve('这里是解析成功:',response.data);}).catch(函数(错误){拒绝('这里是拒绝失败:',错误);});});导出 {getArticlesFromDatabase};
csrfData.test.js
从'react'导入React;从酶"导入{浅,配置};从'enzyme-adapter-react-15'导入适配器;从'柴'导入{期望};从 'axios' 导入 axios;从 'axios-mock-adapter' 导入 MockAdapter;从'../components/common/csrfData'导入{getArticlesFromDatabase};配置({适配器:新适配器()});描述('csrfData',函数(){it('csrfData ', 函数 () {let mock = new MockAdapter(axios);常量数据 = { 响应:真 };mock.onGet('127.0.0.1:8000/api/articles/get-articles-list').reply(200, data);getArticlesFromDatabase.then(function(value) {console.log('getArticlesFromDatabase:',value);});});});
有一个适配器插件可以帮助模拟 axios
https://github.com/ctimmerm/axios-mock-adapter
如果你有返回 Axios 实例的泛型方法,你也可以参考我的要点
https://gist.github.com/abhirathore2006/2bdc5e7e623bc0aa
I'm testing a axios inside the getArticlesFromDatabase.
Seems like I'm doing wrong, cause console shows following message:
(node:36919) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 5): here is reject fail:
(node:36919) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
How to fix it?
csrfData.js
import axios from 'axios';
var getArticlesFromDatabase = new Promise(function(resolve, reject) {
axios.get('127.0.0.1:8000/api/articles/get-articles-list').then(response=>{
resolve('herer is resolve success: ',response.data);
}).catch(function (error) {
reject('herer is reject fail: ',error);
});
});
export {getArticlesFromDatabase};
csrfData.test.js
import React from 'react';
import {shallow, configure} from 'enzyme';
import Adapter from 'enzyme-adapter-react-15';
import {expect} from 'chai';
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import {getArticlesFromDatabase} from '../components/common/csrfData';
configure({adapter: new Adapter()});
describe('csrfData', function () {
it('csrfData ', function () {
let mock = new MockAdapter(axios);
const data = { response: true };
mock.onGet('127.0.0.1:8000/api/articles/get-articles-list').reply(200, data);
getArticlesFromDatabase.then(function(value) {
console.log('getArticlesFromDatabase: ',value);
});
});
});
There is a adapter plugin which helps in mocking the axios
https://github.com/ctimmerm/axios-mock-adapter
you can also refer my gist if you have generic method which returns the Axios Instance
https://gist.github.com/abhirathore2006/2bdc5e7e696e39e2cbf8b1800e33ecfc
这篇关于单元测试:如何在反应中模拟 axios?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!