简体   繁体   English

如何使用Jest在异步调用中测试动作缩减器并进行调度?

[英]How Can I test a an action reducer with an async call and dispatch inside using Jest?

I'm new in Jest and I'm trying to make test to my async action creators. 我是Jest的新手,正在尝试对异步动作创建者进行测试。 The problem is that I only have seen examples of tests where there is a method for the action creator and other separate method for the dispatch. 问题是,我只看到了一些测试示例,其中有一个用于操作创建者的方法和一个用于调度的其他单独方法。 My actions creators have the dispatch as an async callback function, but I can't figure out how to make the test. 我的动作创建者将分派作为异步回调函数,但我不知道如何进行测试。 My Action Reducer looks like this: 我的Action Reducer看起来像这样:

export const postConnection = (connectionUrl, username, password) => {
    return async (dispatch) => {
        const response = await requireAuthActions.post('/db/conexion', JSON.stringify({ connectionUrl, username, password }));
        dispatch({ type: POST_CONNECTION, payload: response.data });
        history.push('/conexiones');
    }
}

And I have trying to do the test script but when I run it it throws me an error. 而且我尝试执行测试脚本,但是当我运行它时,它会引发错误。 The script looks like this: 该脚本如下所示:

describe('Pruebas de Conexiones', () => {
    describe('Action Creators', () => {
        it("Crear conexión", async () => {
            const dispatch = jest.fn();
            const {data} = await postConnection('www.google.com', 'root', 'password')(dispatch);
            dispatch({});
        });
    });
});

And when I try to run the test script it throws me the next error: 当我尝试运行测试脚本时,它将引发下一个错误:

Request failed with status code 401

      at createError (node_modules/axios/lib/core/createError.js:16:15)
      at settle (node_modules/axios/lib/core/settle.js:17:12)
      at IncomingMessage.handleStreamEnd (node_modules/axios/lib/adapters/http.js:237:11)

Is there a way of test actions creators like the mine? 有没有像我这样的测试行动创建者的方法?

EDIT Now I have a mocks file with a mock for axios that looks like this: 编辑现在,我有一个模拟文件,其中包含一个用于axios的模拟文件,如下所示:

const mockAxios = jest.genMockFromModule('axios');

mockAxios.create = jest.fn(() => mockAxios)

export default mockAxios

But now my problems is that I don't know how to implement this in the test file. 但是现在我的问题是我不知道如何在测试文件中实现它。 For now I have something like this: 现在我有这样的事情:

import thunk from 'redux-thunk';
import mockAxios from 'axios';

const middlewares = [thunk];
const mockStore = configureStore(middlewares);

describe('Test de conexiones', () =>{
    describe('Action Creators', () =>{
        it('Agregar conexión', async () =>{
            const store = mockStore({});
            const mockData = {data:123};
            mockAxios.get.mockImplementationOnce(()=>Promise.resolve({data: mockData}));

            const expectedActions = [
                {type: POST_CONNECTION, data: mockData}
            ]
            const dispatch = jest.fn();
            const response = await postConnection('www.google.com','root','password')(dispatch);
        });
    });
});

And it throws me the next error: 这会引发下一个错误:

TypeError: Cannot read property 'data' of undefined

      12 |     return async (dispatch) => {
      13 |         const response = await requireAuthActions.post('/db/conexion', JSON.stringify({ connectionUrl, username, password }));
    > 14 |         dispatch({ type: POST_CONNECTION, payload: response.data });
         |                                                             ^
      15 |         history.push('/conexiones');
      16 |     }
      17 | }

I see 2 approaches possible: using real store or redux-mock-store 我看到两种可能的方法:使用真实商店或redux-mock-store

Steps are similar: 步骤相似:

  1. Set up store. 设置商店。
  2. mock external API like http call or at least requireAuthActions module with some response(successful or failed)(check jest's docs on mocking ) 模拟一些外部API(例如http调用)或至少带有某些响应(成功或失败)的requireAuthActions模块(请检查有关嘲笑的Jest文档
  3. make a pause to await( await Promise.resolve(); , flush-promises or setTimeout(..., 0) ) all async things like Promise.resolve() you mocked in #2. 暂停以等待(#2中嘲笑的所有Promise.resolve()类的异步内容setTimeout(..., 0)以等待await( await Promise.resolve(); flush-promisessetTimeout(..., 0) )。
  4. if you use real store - then check against store(with selectors if you use this level of abstraction) if it contains data you would expect to see based on response you mocked in #2 如果您使用的是真实商店-那么请检查store(如果使用此抽象级别,则使用选择器进行检查),如果其中包含您希望根据在#2中模拟的响应看到的数据
  5. if it's redux-mock-store you cannot verify data in state(so reducers should be tested separately) so just validate list of actions generated - if they meet expectations based on response mocked in #2 or not. 如果是redux-mock-store ,则无法验证状态下的数据(因此,应该分别测试reducer),因此只需验证生成的操作列表-如果它们满足基于#2中redux-mock-store响应的期望,或者不满足。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何测试 vuex 动作,它带有 jest 里面有一个 api 调用? - How can I test vuex action which with jest which has an api call inside it? 我如何测试这个 redux 的玩笑? - how can I test this redux action in jest? 如何使用Jest在vuejs中测试API调用? - How can i test an API call in vuejs using jest? 如何在钩子函数中调用reducer动作 - how to call the reducer action inside hook function 使用 react + hooks,我如何在异步 redux 正确调度后调用/使用“navigate()”? - Using react + hooks, how can i call/use "navigate()" after a async redux dispatch properly? React Redux 工具包 - 我们可以从一个 reducer 的操作调度/调用另一个 reducer 的操作来更改 state 变量 - React Redux Toolkit - Can we Dispatch/Call from one reducer's action to another reducer's action to change state variable 在Redux Reducer内调用一个动作 - Call an action inside the redux reducer 如何解决异步调用中Redux动作创建者中的“未定义”问题? - How to fix “undefined” issue in async call to dispatch in action creator of redux? Dispatch 不将操作发送到减速器 - Dispatch not sending the action to the reducer 如何使用Jest在ES6类方法中测试对redux存储的调度? - How can I test a dispatch to a redux store in an ES6 class method with Jest?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM