DEV Community

palanisamy K
palanisamy K

Posted on

Issues in mocking dispatching event in Jest

We are currently in the process of developing a single-page package that involves the dynamic hiding and displaying of components based on specific conditions. To implement this functionality, we have employed the use of useReducer and useContext. Through the context, we dispatch events to the reducer.
As part of our testing strategy, we need to create a unit test case for a particular scenario. In this case, the requirement is to dispatch an event that loads the second component, and subsequently, we must verify the presence of a specific element.
However, we are encountering challenges in effectively mocking the dispatch event for this scenario.

Do we have a any solution for this?

PageContext.tsx:

export const PageContext = React.createContext({} as PageContextType);

export const PageContextProvider = ({ children }: PageContextProviderProps) => {
const [pages, pagesDispatch] = useReducer(pageReducer, pageState);

return (
{children}
);
};

Reducerfile :

export const pageState = {
currentPage:
};

export const pageReducer = (state, action) => {
switch (action.type) {
case "component1":
return {
...state,
currentPage:
};
case "component2":
return {
...state,
currentPage:
}
case "componentDefault":
return {
...state,
currentPage:
};
default:
return state;
}
};

Dispatchevent:

const pageContext = React.useContext(PageContext);

pageContext?.pagesDispatch &&
pageContext.pagesDispatch({
type: "{component2}",
payload: { text, text2 }
});

Testingfile:

const mockDispatch = jest.fn();

jest.mock("../../context/PageContext", () => ({
...jest.requireActual("../../context/PageContext"),
PageContext: {
Consumer: ({ children }) => children({ pagesDispatch: mockDispatch })
}
}));

describe("testcomponent2", () => {
test("should dispatch component2 when onClickContinue is called", () => {
//const addItem = jest.fn();
render(



);
fireEvent.click(screen.getByText("Continue"));
expect(mockDispatch).toHaveBeenCalledTimes(1);
});
});

Top comments (0)