reactjs - Redux-actions Jest 测试
问题描述
我使用“redux-actions”并在 Redux 中有异步操作创建器我尝试编写单元测试,但出现错误:
超时 - 在 jest.setTimeout 指定的 100000 毫秒超时内未调用异步回调。
这可能是由于在我的操作中调用了计时器。我该如何解决这个错误?
actions.js
import axios from 'axios';
import { createAction } from 'redux-actions';
export const loadingNewsRequest = createAction('LOADING_NEWS_REQUEST');
export const loadingNewsSuccess = createAction('LOADING_NEWS_SUCCESS');
export const loadingNewsFailure = createAction('LOADING_NEWS_FAILURE');
const path = 'http://127.0.0.1:7000';
const timeout = 5000;
const loadingTimeout = 60000;
export const loadNews = () => async (dispatch) => {
dispatch(loadingNewsRequest());
try {
const response = await axios.get(`${path}/news`, { timeout });
const timer = setTimeout(() => loadNews()(dispatch), loadingTimeout);
dispatch(loadingNewsSuccess({ allNews: response.data, timer }));
} catch (err) {
const timer = setTimeout(() => loadNews()(dispatch), loadingTimeout);
dispatch(loadingNewsFailure({ err: err.message, timer }));
}
};
actions.test.js
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import * as actions from './index';
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
describe('loadNews', () => {
const newsData = [ { x: 1}, { y: 2} ];
it('returns data when sendMessage is called', async (done) => {
const mock = new MockAdapter(axios);
mock.onGet('http://127.0.0.1:7000/news').reply(200, newsData);
jest.setTimeout(100000);
const expectedActions = [
actions.loadingNewsRequest(),
actions.loadingNewsSuccess(
{
allNews: newsData,
timer: 4,
},
),
];
const initialState = { allNews: [], timer: null };
const store = mockStore(initialState);
await store.dispatch(actions.loadNews());
expect(store.getActions()).toEqual(expectedActions);
});
});
解决方案
async
函数返回一个被 Jest 使用的 Promise。done
回调是编写异步测试的传统方式。它不应该与 Promise 和async
函数同时使用。
done
以 Jest 处理异步测试的方式优先于 Promise。由于done
从不调用,它等待超时并失败。
它应该是:
it('returns data when sendMessage is called', async () => {
...
100000对于超时来说太多了,如果有异步过程,它会在几秒钟内完成。15000 足以确保测试永远不会完成。
推荐阅读
- c# - 通过 SetActive() 在 Unity 中隐藏对象
- python - 从空间数据创建二维数组
- python - Pandas groupby 计算天数
- c++ - 共享内存崩溃安全吗?
- vba - VBA代码根据当前日期打开名称中带有日期的文件
- python - Python 在文件中找到不存在的字符,用非预期字符替换(非英文字符的编码问题)
- c# - ASP.NET Core 中的 WebViewPage.InitializePage() 等价物是什么?
- powershell - 遍历数组并获取所有用户的单元格
- python - DataFrame 来自现有列的新列
- firebase - 如何更新存储在firestore中的发布者信息,以及使用flutter应用程序