Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

189
Views
Why can't I test for errors in redux-toolkit reducer with jest?
const cartsSlice = createSlice({
  name: CARTS,
  initialState,
  reducers: {
    increaseCartItemQuantityById: (state, { payload }: PayloadAction<{ cartItemId: number }>) => {
      const targetIndex = state.carts.value.findIndex(
        (cartItem) => cartItem.id === payload.cartItemId,
      );

      if (targetIndex === -1) throw new Error('mismatched id');

      state.carts.value[targetIndex].quantity = state.carts.value[targetIndex].quantity + 1;
    },

I want to test whether a reducer throws an error well. So I try to test using thThrow, thThrowError etc..

I tried it

it('throw error test', () => {
      const MISMATCHED_ID = 1;

      const error = new Error('mismatched id');

      expect(
        cartsReducer(
          cartsReducerInitialState,
          increaseCartItemQuantityById({ cartItemId: MISMATCHED_ID }),
        ),
      )
    .toThrowError(error); // fail
    .toThrow(error); // fail
    .toThrowErrror('mismatched id'); // fail
    .toThrowErrror(/mismatched id/); // fail
    .toHaveErrorMessage(/mismatched id/); // fail
    .toHaveErrorMessage('mismatched id'); // fail
    });
  });

All these ways are failed... It only returned this message

FAIL store/modules/carts/tests/cartsReducer.test.ts ● › increaseCartItemQuantityById › throw error test

mismatched id

  37 |     },
  38 |   } as CartsReducerState,
> 39 |   reducers: {
     |                        ^
  40 |     addCartItem: (state, { payload }: PayloadAction<{ newCartItem: CartItem }>) => {
  41 |       state.carts.value = [...state.carts.value, payload.newCartItem];
  42 |     },

  at increaseCartItemQuantityById (store/modules/carts/slice.ts:39:43)
  at recipe (node_modules/@reduxjs/toolkit/src/createReducer.ts:280:20)
  at Immer.produce (node_modules/immer/src/core/immerClass.ts:94:14)
  at node_modules/@reduxjs/toolkit/src/createReducer.ts:279:18
      at Array.reduce (<anonymous>)
  at reducer (node_modules/@reduxjs/toolkit/src/createReducer.ts:246:25)
  at Object.reducer [as cartsReducer] (node_modules/@reduxjs/toolkit/src/createSlice.ts:325:14)
  at Object.<anonymous> (store/modules/carts/__tests__/cartsReducer.test.ts:55:32)
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!