diff --git a/packages/toolkit/src/mapBuilders.ts b/packages/toolkit/src/mapBuilders.ts index 559e234d03..90bbe7d50e 100644 --- a/packages/toolkit/src/mapBuilders.ts +++ b/packages/toolkit/src/mapBuilders.ts @@ -140,7 +140,7 @@ export function executeReducerBuilderCallback( ) { if (process.env.NODE_ENV !== 'production') { /* - to keep the definition by the user in line with actual behavior, + to keep the definition by the user in line with actual behavior, we enforce `addCase` to always be called before calling `addMatcher` as matching cases take precedence over matchers */ @@ -159,9 +159,14 @@ export function executeReducerBuilderCallback( typeof typeOrActionCreator === 'string' ? typeOrActionCreator : typeOrActionCreator.type + if (!type) { + throw new Error( + '`builder.addCase` cannot be called with an empty action type' + ) + } if (type in actionsMap) { throw new Error( - 'addCase cannot be called with two reducers for the same action type' + '`builder.addCase` cannot be called with two reducers for the same action type' ) } actionsMap[type] = reducer diff --git a/packages/toolkit/src/tests/createReducer.test.ts b/packages/toolkit/src/tests/createReducer.test.ts index 5c3a181168..4fb840f696 100644 --- a/packages/toolkit/src/tests/createReducer.test.ts +++ b/packages/toolkit/src/tests/createReducer.test.ts @@ -460,7 +460,7 @@ describe('createReducer', () => { .addCase(decrement, (state, action) => state - action.payload) ) ).toThrowErrorMatchingInlineSnapshot( - `"addCase cannot be called with two reducers for the same action type"` + '"`builder.addCase` cannot be called with two reducers for the same action type"' ) expect(() => createReducer(0, (builder) => @@ -470,7 +470,25 @@ describe('createReducer', () => { .addCase(decrement, (state, action) => state - action.payload) ) ).toThrowErrorMatchingInlineSnapshot( - `"addCase cannot be called with two reducers for the same action type"` + '"`builder.addCase` cannot be called with two reducers for the same action type"' + ) + }) + + test('will throw if an empty type is used', () => { + const customActionCreator = (payload: number) => ({ + type: 'custom_action', + payload, + }) + customActionCreator.type = "" + expect(() => + createReducer(0, (builder) => + builder.addCase( + customActionCreator, + (state, action) => state + action.payload + ) + ) + ).toThrowErrorMatchingInlineSnapshot( + '"`builder.addCase` cannot be called with an empty action type"' ) }) })