下面的代码段是我的交易操作。我可以使用__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([]);
});
});
答案 0 :(得分:0)
jest.resetModules();
可以解决模块重新导入的问题。
重置模块注册表-所有必需模块的缓存。这对于隔离测试之间局部状态可能冲突的模块很有用。
答案 1 :(得分:0)
我已经广泛使用redux-mock-store https://github.com/dmitry-zaets/redux-mock-store来测试同步和异步动作创建者