[英]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: 步骤相似:
requireAuthActions
module with some response(successful or failed)(check jest's docs on mocking ) 模拟一些外部API(例如http调用)或至少带有某些响应(成功或失败)的requireAuthActions
模块(请检查有关嘲笑的Jest文档 ) 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-promises
或setTimeout(..., 0)
)。 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.