首页 > 解决方案 > 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);
  });
});

标签: reactjsunit-testingtestingreduxjestjs

解决方案


async函数返回一个被 Jest 使用的 Promise。done回调是编写异步测试的传统方式。它不应该与 Promise 和async函数同时使用。

done以 Jest 处理异步测试的方式优先于 Promise。由于done从不调用,它等待超时并失败。

它应该是:

  it('returns data when sendMessage is called', async () => {
  ...

100000对于超时来说太多了,如果有异步过程,它会在几秒钟内完成。15000 足以确保测试永远不会完成。


推荐阅读