【问题标题】:Redux-actions Jest testingRedux-actions Jest 测试
【发布时间】:2020-12-09 13:06:05
【问题描述】:

我使用“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);
  });
});

【问题讨论】:

    标签: reactjs unit-testing testing redux jestjs


    【解决方案1】:

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

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

    应该是:

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

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

    【讨论】:

      猜你喜欢
      • 2019-03-22
      • 2018-09-14
      • 2017-09-23
      • 2020-09-26
      • 1970-01-01
      • 2018-09-20
      • 2018-01-04
      • 2018-06-10
      • 1970-01-01
      相关资源
      最近更新 更多