简体   繁体   中英

How to Test Redux Thunk Async Action with Jest Mock Module

The code snippet below is my transactions actions. I can use __mocks__ to mock doFetchTransactions function but which only covers the happy case didFetchTransactionsSuccessful . How to make it also covers the failed case?

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
  };
};

What I'm trying to do but failed (I think it is caused by require only load dependency once),

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([]);
  });
});
jest.resetModules();

Can solve module re-import issue.

Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM