Redux: Jest detects errors when dispatching an action from a Class method

Viewed 96

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')?

1 Answers

This most likely means you have a circular import error, and the slice file hasn't loaded yet when the store is being initialized.

This is probably caused by importing the store directly into that TestClass file. This is actually one of the reasons why we specifically say you should not import the store directly into other files.

Generally, you shouldn't be using classes like this in a Redux app in the first place. There's no real benefit or need to use them.

If you absolutely must reference the store (which should only be done as a last resort), we have some suggestions on how to work around this.

Related