Unit test: How to mock axios in react?

匿名 (未验证) 提交于 2019-12-03 01:40:02

问题:

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

回答1:

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



回答2:

Even i struggled a lot for this. But eventually i got the solution.

Here it is:

    import { .. } from '../yourServices';     jest.mock('axios');     var axios = require('axios');     //If you use get, post write as below, If you are using axios(config) dont need to mock below     jest.mock('axios', () => ({ post: jest.fn(),create: jest.fn() })); 

Then in your tests

    describe('Sample Test', () => {         it('Should get - Test', async () => {              const mockedResponse = Promise.resolve({                Response data             });           //Make sure you mock the the functions at import (above) before using here.                 //Post case             axios.post.mockResolvedValue(mockedResponse);            //Create Case             axios.create.mockResolvedValue(mockedResponse);            //get ....              //If you use default axios(url, config) or axios(config)             axios.mockResolvedValue(mockedResponse);              //Your code         }); }); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!