@@ -12,6 +12,8 @@ import type {
12
12
ReducerCreatorEntry ,
13
13
ReducerCreators ,
14
14
ReducerDefinition ,
15
+ ReducerDetails ,
16
+ ReducerHandlingContext ,
15
17
SliceActionType ,
16
18
ThunkAction ,
17
19
WithSlice ,
@@ -943,6 +945,69 @@ describe('createSlice', () => {
943
945
expect ( selectValue ( store . getState ( ) ) ) . toBe ( 1 )
944
946
} )
945
947
} )
948
+ describe ( 'context methods throw errors if used incorrectly' , ( ) => {
949
+ const makeSliceWithHandler = (
950
+ handle : ReducerCreator < typeof loaderCreatorType > [ 'handle' ] ,
951
+ ) => {
952
+ const createAppSlice = buildCreateSlice ( {
953
+ creators : {
954
+ loader : {
955
+ type : loaderCreatorType ,
956
+ create ( reducers ) {
957
+ return {
958
+ _reducerDefinitionType : loaderCreatorType ,
959
+ ...reducers ,
960
+ }
961
+ } ,
962
+ handle,
963
+ } satisfies ReducerCreator < typeof loaderCreatorType > ,
964
+ } ,
965
+ } )
966
+ return createAppSlice ( {
967
+ name : 'loader' ,
968
+ initialState : { } as Partial < Record < string , true > > ,
969
+ reducers : ( create ) => ( {
970
+ addLoader : create . loader ( { } ) ,
971
+ } ) ,
972
+ } )
973
+ }
974
+ test ( 'context.addCase throws if called twice for same type' , ( ) => {
975
+ expect ( ( ) =>
976
+ makeSliceWithHandler ( ( _details , _def , context ) => {
977
+ context . addCase ( 'foo' , ( ) => { } ) . addCase ( 'foo' , ( ) => { } )
978
+ } ) ,
979
+ ) . toThrowErrorMatchingInlineSnapshot (
980
+ `[Error: \`context.addCase\` cannot be called with two reducers for the same action type: foo]` ,
981
+ )
982
+ } )
983
+ test ( 'context.addCase throws if empty action type' , ( ) => {
984
+ expect ( ( ) =>
985
+ makeSliceWithHandler ( ( _details , _def , context ) => {
986
+ context . addCase ( '' , ( ) => { } )
987
+ } ) ,
988
+ ) . toThrowErrorMatchingInlineSnapshot (
989
+ `[Error: \`context.addCase\` cannot be called with an empty action type]` ,
990
+ )
991
+ } )
992
+ test ( 'context.exposeAction throws if called twice for same reducer name' , ( ) => {
993
+ expect ( ( ) =>
994
+ makeSliceWithHandler ( ( _details , _def , context ) => {
995
+ context . exposeAction ( ( ) => { } ) . exposeAction ( ( ) => { } )
996
+ } ) ,
997
+ ) . toThrowErrorMatchingInlineSnapshot (
998
+ `[Error: context.exposeAction cannot be called twice for the same reducer definition: addLoader]` ,
999
+ )
1000
+ } )
1001
+ test ( 'context.exposeCaseReducer throws if called twice for same reducer name' , ( ) => {
1002
+ expect ( ( ) =>
1003
+ makeSliceWithHandler ( ( _details , _def , context ) => {
1004
+ context . exposeCaseReducer ( { } ) . exposeCaseReducer ( { } )
1005
+ } ) ,
1006
+ ) . toThrowErrorMatchingInlineSnapshot (
1007
+ `[Error: context.exposeCaseReducer cannot be called twice for the same reducer definition: addLoader]` ,
1008
+ )
1009
+ } )
1010
+ } )
946
1011
} )
947
1012
} )
948
1013
0 commit comments