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



下面的代码片段是我的交易操作。我可以使用__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([]);
});
});

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

jest.resetModules();

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

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

最新更新