在 Redux 动作中模拟一个函数

Mocking a function inside of a Redux action

我正在为我的 redux 操作编写测试。在我的一个复杂动作中,我有一个功能,例如aRandomFunction 我想嘲笑。如何添加编写模拟在 fetchAction 中使用的函数的测试?谢谢!你可以看下面的例子。

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';

jest.mock('../../api/handleError');
jest.mock('../../api/handleResponse');

let store;

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

beforeEach(() => {
  store = mockStore({});
  fetchMock.restore();
});

const aRandomAction = () => ({
  type: "RANDOM_ACTION",
})

const aRandomFunction = (data, dispatch) => {
  if (data.isTrue) {
    dispatch(aRandomAction);
  }
};

export const fetchAction = () => {
  return (dispatch) => {
    dispatch(requestAction());
    return fetch('sampleApi/foo')
      .then(response => handleResponse(response))
      .then((json) => {
        aRandomFunction(json.data, dispatch);
        dispatch(receiveAction(json.data));
      })
      .catch(error => handleError(error));
  };
};

describe('testing the fetch Action', () => {
  test('testing the fetch action', () => {
    const expectedActions = [
      { type: "REQUEST_ACTION" },
      { type: "RECEIVE_ACTION", data: "payload" },
    ];
    return store.dispatch(fetchAction()).then(() => {
      expect(store.getActions()).toEqual(expectedActions);
    });
  });
});

在这种情况下你不能模拟 aRandomFunction,因为它没有导出。虽然这在 Jest's documentation, please note in the examples 中没有明确说明只有可导入的代码才能用 Jest 模拟。您可以专注于测试 fetchAction 的最终结果,而中间发生的事情并不重要。不测试它完全没问题,因为它是实现细节,也就是说,它只定义了 fetchAction 用来实现其目标的方法,它可能会随着时间的推移而改变并破坏你的测试,即使 [=13] 的目标=] 不断正确实现。

但是如果能够测试 aRandomFunction 对您来说很重要,则必须将其移动到外部文件,然后从那里导出。这样做之后,您将能够像模拟其他依赖项一样模拟它,例如 handleErrorhandleResponse。如果您的测试用例需要,您甚至可以 define a mock implementation,例如:

随机-function.js

const aRandomAction = () => ({
  type: "RANDOM_ACTION",
});

const aRandomFunction = (data, dispatch) => {
  if (data.isTrue) {
    dispatch(aRandomAction());
  }
}

export default aRandomFunction;

your-test-case.spec.js(将其与问题示例中的测试用例一起放置)

import aRandomFunction from "./random-function";

jest.mock("./random-function");

aRandomFunction.mockImplementation((data, dispatch) => {
  dispatch({ type: "MOCK_ACTION" );
});