Skip to content

Commit f63b862

Browse files
authored
Merge pull request #3572 from chawes13/3570-throw-error-on-empty-type-value
2 parents fc71b51 + 5c82a28 commit f63b862

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

packages/toolkit/src/mapBuilders.ts

+7-2
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ export function executeReducerBuilderCallback<S>(
140140
) {
141141
if (process.env.NODE_ENV !== 'production') {
142142
/*
143-
to keep the definition by the user in line with actual behavior,
143+
to keep the definition by the user in line with actual behavior,
144144
we enforce `addCase` to always be called before calling `addMatcher`
145145
as matching cases take precedence over matchers
146146
*/
@@ -159,9 +159,14 @@ export function executeReducerBuilderCallback<S>(
159159
typeof typeOrActionCreator === 'string'
160160
? typeOrActionCreator
161161
: typeOrActionCreator.type
162+
if (!type) {
163+
throw new Error(
164+
'`builder.addCase` cannot be called with an empty action type'
165+
)
166+
}
162167
if (type in actionsMap) {
163168
throw new Error(
164-
'addCase cannot be called with two reducers for the same action type'
169+
'`builder.addCase` cannot be called with two reducers for the same action type'
165170
)
166171
}
167172
actionsMap[type] = reducer

packages/toolkit/src/tests/createReducer.test.ts

+20-2
Original file line numberDiff line numberDiff line change
@@ -460,7 +460,7 @@ describe('createReducer', () => {
460460
.addCase(decrement, (state, action) => state - action.payload)
461461
)
462462
).toThrowErrorMatchingInlineSnapshot(
463-
`"addCase cannot be called with two reducers for the same action type"`
463+
'"`builder.addCase` cannot be called with two reducers for the same action type"'
464464
)
465465
expect(() =>
466466
createReducer(0, (builder) =>
@@ -470,7 +470,25 @@ describe('createReducer', () => {
470470
.addCase(decrement, (state, action) => state - action.payload)
471471
)
472472
).toThrowErrorMatchingInlineSnapshot(
473-
`"addCase cannot be called with two reducers for the same action type"`
473+
'"`builder.addCase` cannot be called with two reducers for the same action type"'
474+
)
475+
})
476+
477+
test('will throw if an empty type is used', () => {
478+
const customActionCreator = (payload: number) => ({
479+
type: 'custom_action',
480+
payload,
481+
})
482+
customActionCreator.type = ""
483+
expect(() =>
484+
createReducer(0, (builder) =>
485+
builder.addCase(
486+
customActionCreator,
487+
(state, action) => state + action.payload
488+
)
489+
)
490+
).toThrowErrorMatchingInlineSnapshot(
491+
'"`builder.addCase` cannot be called with an empty action type"'
474492
)
475493
})
476494
})

0 commit comments

Comments
 (0)