如何使用Jest Mock模块测试Redux Thunk异步操作

时间:2018-09-16 04:43:14

标签: javascript jestjs

下面的代码段是我的交易操作。我可以使用__mocks__来模拟doFetchTransactions函数,但这仅涵盖了快乐的情况didFetchTransactionsSuccessful。如何使它也涵盖失败的案例?

import { doFetchTransactions as networkFetchTransactions } from "../../utilities/api";

export const ACTION_TYPE = {
  FETCH_TRANSACTIONS_SUCCESS: "FETCH_TRANSACTIONS_SUCCESS",
  FETCH_TRANSACTIONS_FAILED: "FETCH_TRANSACTIONS_FAILED"
};

export const doFetchTransactions = () => {
  return dispatch => {
    const handleReslove = response => {
      const transactions = response;

      dispatch(didFetchTransactionsSuccessful(transactions));
    };

    const handleReject = error => {
      dispatch(didFetchTransactionsFailed());
    };

    return networkFetchTransactions(handleReslove, handleReject);
  };
};

const didFetchTransactionsSuccessful = transactions => {
  return {
    type: ACTION_TYPE.FETCH_TRANSACTIONS_SUCCESS,
    transactions
  };
};

const didFetchTransactionsFailed = () => {
  return {
    type: ACTION_TYPE.FETCH_TRANSACTIONS_FAILED
  };
};

我正在尝试做的但失败了(我认为这是由require仅加载一次依赖项引起的),

import { mockStore } from "../store/mockStore";

describe("Actions for Transactions", () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });

  it("should create correct action when transaction fetching success", async () => {
    const mockApiFunctions = () => ({
      doFetchTransactions: jest.fn(handleSuccess => handleSuccess([]))
    });

    jest.mock("../../utilities/api", () => mockApiFunctions());

    const { doFetchTransactions } = require("./transactions");
    const store = mockStore();
    await store.dispatch(doFetchTransactions());
    const actions = store.getActions();

    expect(actions).toEqual([{ transactions: [], type: "FETCH_TRANSACTIONS_SUCCESS" }]);
  });

  it("should create correct action when transaction fetching failed", async () => {
    const mockApiFunctions = () => ({
      doFetchTransactions: jest.fn((_, handleReject) => handleReject("Error"))
    });

    jest.mock("../../utilities/api", () => mockApiFunctions());
    const { doFetchTransactions } = require("./transactions");
    const store = mockStore();
    await store.dispatch(doFetchTransactions());
    const actions = store.getActions();
    expect(actions).toEqual([]);
  });
});

2 个答案:

答案 0 :(得分:0)

jest.resetModules();

可以解决模块重新导入的问题。

  

重置模块注册表-所有必需模块的缓存。这对于隔离测试之间局部状态可能冲突的模块很有用。

答案 1 :(得分:0)

我已经广泛使用redux-mock-store https://github.com/dmitry-zaets/redux-mock-store来测试同步和异步动作创建者