How to Test Redux Thunk Async Action with Jest Mock Function

961 views javascript
1

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

answered question

2 Answers

3

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.

posted this
5

I have extensively used redux-mock-store https://github.com/dmitry-zaets/redux-mock-store to test both synchronous and asynchronous action creators

posted this

Have an answer?

JD

Please login first before posting an answer.