I have the following Class to handle errors.
import { store } from 'redux/store';
import { openErrorMessage } from 'redux/slices/errorMessage';
export default class TestClass {
errorReceived(errorMessage: string): void {
store.dispatch(openErrorMessage({ message: errorMessage }));
}
}
My goal is to dispatch an action from a non React component class like the TestClass.
Here is what's inside the errorMessageSlice.
import { createSlice } from '@reduxjs/toolkit';
export type ErrorMessageState = {
isOpen?: boolean;
message: string;
};
const initialState: ErrorMessageState = {
isOpen: false,
message: '',
};
const errorMessageSlice = createSlice({
name: 'errorMessage',
initialState,
reducers: {
openErrorMessage(state: ErrorMessageState, { payload }: { payload: ErrorMessageState; type: string }) {
state.isOpen = true;
state.message = payload.message;
},
closeErrorMessage(state: ErrorMessageState) {
state.isOpen = false;
state.message = '';
},
},
});
export default errorMessageSlice;
export const { openErrorMessage, closeErrorMessage } = errorMessageSlice.actions;
And the rootReducer.
import { AnyAction, combineReducers } from 'redux';
import { openErrorMessage } from './slices/errorMessage';
const appReducer = combineReducers({
// More Reducers
errorMessage: errorMessageSlice.reducer,
});
const rootReducer = (state: ReturnType<typeof appReducer> | undefined, action: AnyAction) => {
return appReducer(state, action);
};
export default rootReducer;
When I execute errorReceived method from a client, it doesn't throw error.
But when I run tests with Jest, I have the following errors.
TypeError: Cannot read properties of undefined (reading 'reducer')
otherReducerName: otherReducerNameSlice.reducer,
at Object. (src/redux/rootReducer.ts:28:47)
at Object. (src/redux/store.ts:2:1)
I found the problem is the errorReceived which directory access the store object and dispatches an action.
store.dispatch(openErrorMessage({ message: errorMessage }));
How can I solve this problem of Jest giving Cannot read properties of undefined (reading 'reducer')?