【问题标题】:Mocking a function inside of a Redux action在 Redux 操作中模拟一个函数
【发布时间】:2019-07-13 15:54:13
【问题描述】:

我正在为我的 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 的来源吗?是从其他文件导入的吗?
  • @fmoliveira,使用内联函数更新。

标签: javascript reactjs redux jestjs redux-thunk


【解决方案1】:

在这种情况下,您不能模拟 aRandomFunction,因为它没有被导出。尽管Jest's documentation 中没有明确说明这一点,但请注意in the examples 只有可导入的代码才能被 Jest 模拟。您可以专注于测试fetchAction 的最终结果,中间发生的事情无关紧要。不测试它是完全可以的,因为它是实现细节,也就是说,它只定义了fetchAction 用来实现其目标的手段,即使fetchAction 的目标一直存在,它也可能随着时间的推移而改变并破坏你的测试正确实现。

但如果能够测试aRandomFunction 对您很重要,您将不得不将其移动到外部文件,然后从那里导出。完成此操作后,您将能够像模拟其他依赖项一样模拟它,例如 handleErrorhandleResponse。如果您的测试用例需要,您甚至可以define a mock implementation,例如:

随机函数.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" );
});

【讨论】:

    猜你喜欢
    • 2021-02-23
    • 2017-09-05
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 2018-09-04
    • 2019-03-25
    • 2019-04-19
    相关资源
    最近更新 更多