Asynchronous 使用Jest在Redux中测试异步动作创建者(使用axios)

Asynchronous 使用Jest在Redux中测试异步动作创建者(使用axios),asynchronous,redux,mocking,jestjs,axios,Asynchronous,Redux,Mocking,Jestjs,Axios,在Redux中为异步操作创建者创建测试时遇到问题。我使用axios进行抓取,使用Jest进行测试。数据已正确加载到应用程序本身中。只是我正在写的测试出错了 我遵循了关于测试的Redux文档,但在那里使用了它。我很难把它转到我的箱子里 我尝试了两种都失败的方法: 使用moxios模拟axios 使用jest.mock('axios') 这是我的动作创建者中的代码: import { BG_LOAD_START, BG_LOAD_SUCCESS, BG_LOAD_FAIL

在Redux中为异步操作创建者创建测试时遇到问题。我使用axios进行抓取,使用Jest进行测试。数据已正确加载到应用程序本身中。只是我正在写的测试出错了

我遵循了关于测试的Redux文档,但在那里使用了它。我很难把它转到我的箱子里

我尝试了两种都失败的方法:

  • 使用
    moxios
    模拟axios
  • 使用jest.mock('axios')
  • 这是我的动作创建者中的代码:

    import {
        BG_LOAD_START, 
        BG_LOAD_SUCCESS, 
        BG_LOAD_FAILURE} from './types'
    
    import axios from 'axios'
    
    export const bgLoad = (url, pictureNumber=0) => {
        return dispatch => {
            dispatch(bgLoadStart());
    
            return axios.get(url, {
                headers: {
                    Authorization: `Bearer ${process.env.REACT_APP_API_KEY}`
                }
            })
                .then(res => dispatch(bgLoadSuccess(res.data.photos[pictureNumber], res.data.name, res.data.url)))
                .catch(err => dispatch(bgLoadFailure(err)))
        }
    }
    
    const bgLoadStart = () => {
        return {
            type: BG_LOAD_START
        }
    }
    
    const bgLoadSuccess = (bgImage, name, url) => {
        return {
            type: BG_LOAD_SUCCESS,
            payload: {
                bgImage,
                name,
                url
            }
        }
    }
    
    const bgLoadFailure = error => {
        return {
            type: BG_LOAD_FAILURE,
            payload: {
                ...error
            }
        }
    }
    
    以下是我的测试结果:

    import configureStore from 'redux-mock-store'
    import thunk from 'redux-thunk'
    import {BG_LOAD_START, BG_LOAD_SUCCESS} from '../types'
    import {bgLoad} from '../bgLoad'
    import moxios from 'moxios'
    
    const middlewares = [thunk];
    const mockStore = configureStore(middlewares);
    // jest.mock('axios');
    
    describe(`async bgLoad action`, ()=> {
    
            beforeEach(()=>{
                moxios.install()
            })
    
            afterEach(()=>{
                moxios.uninstall()
            })
    
            it(`creates BG_LOAD_SUCCESS when data has been fetched`, ()=> {
            const fetchedData = [{
                image: 'this is example image',
                name: 'my name is image',
                url: 'this is example link'
            }]
    
            moxios.wait(()=>{
                const request = moxios.requests.mostRecent();
                request.respondWith({
                    status: 200,
                    response: fetchedData
                })
            })
            // axios.get.mockResolvedValue(fetchedData);
    
            const expectedActions = [
                {type: BG_LOAD_START},
                {type: BG_LOAD_SUCCESS,
                    payload: {
                        bgImage: fetchedData[0].image,
                        name: fetchedData[0].name,
                        url: fetchedData[0].url,
                    }
                }
            ]
    
            const store = mockStore({});
    
            return store.dispatch(bgLoad()).then(()=>{
                    expect(store.getActions()).toEqual(expectedActions)
                })
        })
    })
    
    以下是我从控制台得到的响应:

    Expected value to equal:
          [{"type": "BG_LOAD_START"}, {"payload": {"bgImage": "this is example image", "name": "my name is image", "url": "this is example link"}, "type": "BG_LOAD_SUCCESS"}]
        Received:
          [{"type": "BG_LOAD_START"}, {"payload": {}, "type": "BG_LOAD_FAILURE"}]
    

    下面是使用jest.mock的解决方案

    actionCreators.ts

    从“/types”导入{BG_LOAD_START,BG_LOAD_SUCCESS,BG_LOAD_FAILURE};
    从“axios”导入axios;
    导出常量bgLoad=(url,PictureEnumber=0)=>{
    返回调度=>{
    调度(bgLoadStart());
    返回轴
    .get(url{
    标题:{
    授权:`Bearer${process.env.REACT\u APP\u API\u KEY}`
    }
    })
    。然后(res=>dispatch(bgloadsucces(res.data.photos[pictureNumber],res.data.name,res.data.url)))
    .catch(err=>dispatch(bgLoadFailure(err));
    };
    };
    常量bgLoadStart=()=>{
    返回{
    类型:BG\U加载\U启动
    };
    };
    const bgLoadSuccess=(bgImage、名称、url)=>{
    返回{
    类型:BG\u加载成功,
    有效载荷:{
    bgImage,
    名称
    网址
    }
    };
    };
    const bgLoadFailure=错误=>{
    返回{
    类型:BG_加载_故障,
    有效载荷:{
    …错误
    }
    };
    };
    
    actionCreators.spec.ts

    从“redux模拟存储”导入配置存储;
    从'redux-thunk'导入thunk,{ThunkDispatch};
    从“axios”导入axios;
    从“/types”导入{BG_LOAD_START,BG_LOAD_SUCCESS};
    从“/actionCreators”导入{bgLoad};
    从'redux'导入{AnyAction};
    const middleware=[thunk];
    
    const mockStore=configureStore

    Bump。我也尝试过“axios模拟适配器”,这可能是朝着正确方向迈出的一步,但由于模拟axios请求,我仍然会遇到“BG_加载_失败”。你知道为什么我从来没有得到“成功”的回复吗?