单元测试:如何在react中模拟 axios?

IT技术 reactjs unit-testing
2021-05-13 05:45:57

我正在测试getArticlesFromDatabase 中的 axios

好像我做错了,导致控制台显示以下消息:

(节点:36919)UnhandledPromiseRejectionWarning:未处理的Promise拒绝(拒绝ID:5):这里是拒绝失败:(
节点:36919)DeprecationWarning:不推荐使用未处理的Promise拒绝。将来,未处理的Promise拒绝将使用非零退出代码终止 Node.js 进程。

如何解决?


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

    });

});
2个回答

有一个适配器插件可以帮助模拟 axios

https://github.com/ctimmerm/axios-mock-adapter

如果你有返回 Axios 实例的通用方法,你也可以参考我的要点

https://gist.github.com/abhirathore2006/2bdc5e7e696e39e2cbf8b1800e33ecfc

甚至我也为此付出了很多努力。但最终我得到了解决方案。

这里是:

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

然后在你的测试中

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