Skip to content

Commit

Permalink
Merge pull request #3572 from chawes13/3570-throw-error-on-empty-type…
Browse files Browse the repository at this point in the history
…-value
  • Loading branch information
markerikson authored Aug 26, 2023
2 parents fc71b51 + 5c82a28 commit f63b862
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
9 changes: 7 additions & 2 deletions packages/toolkit/src/mapBuilders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ export function executeReducerBuilderCallback<S>(
) {
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
*/
Expand All @@ -159,9 +159,14 @@ export function executeReducerBuilderCallback<S>(
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
Expand Down
22 changes: 20 additions & 2 deletions packages/toolkit/src/tests/createReducer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) =>
Expand All @@ -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"'
)
})
})
Expand Down

0 comments on commit f63b862

Please sign in to comment.