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)