diff --git a/src/decorators/dispatch.spec.ts b/src/decorators/dispatch.spec.ts index a1a0261..2465872 100644 --- a/src/decorators/dispatch.spec.ts +++ b/src/decorators/dispatch.spec.ts @@ -34,6 +34,8 @@ describe('@dispatch', () => { const { value = null, instanceProperty = null } = action.payload || {}; return Object.assign({}, state, { value, instanceProperty }); + case 'CONDITIONAL_DISPATCH_TEST': + return { ...state, ...action.payload }; default: return state; } @@ -58,6 +60,23 @@ describe('@dispatch', () => { }; } + @dispatch() + conditionalDispatchMethod( + shouldDispatch: boolean + ): PayloadAction | false { + if (shouldDispatch) { + return { + type: 'CONDITIONAL_DISPATCH_TEST', + payload: { + value: 'Conditional Dispatch Action', + instanceProperty: this.instanceProperty, + }, + }; + } else { + return false; + } + } + @dispatch() boundProperty = (value: string): PayloadAction => ({ type: 'TEST', @@ -89,6 +108,35 @@ describe('@dispatch', () => { ).toHaveBeenCalledWith(expectedArgs); }); + it('should not call dispatch', () => { + const stateBeforeAction = NgRedux.instance && NgRedux.instance.getState(); + const result = instance.conditionalDispatchMethod(false); + expect(result).toBe(false); + expect(NgRedux.instance).toBeTruthy(); + expect(NgRedux.instance && NgRedux.instance.getState()).toEqual( + stateBeforeAction + ); + }); + + it('should call dispatch with result of function normally', () => { + const result = instance.conditionalDispatchMethod(true); + expect(result.type).toBe('CONDITIONAL_DISPATCH_TEST'); + expect(result.payload && result.payload.value).toBe( + 'Conditional Dispatch Action' + ); + expect(result.payload && result.payload.instanceProperty).toBe('test'); + expect(NgRedux.instance).toBeTruthy(); + expect( + NgRedux.instance && NgRedux.instance.dispatch + ).toHaveBeenCalledWith({ + type: 'CONDITIONAL_DISPATCH_TEST', + payload: { + value: 'Conditional Dispatch Action', + instanceProperty: 'test', + }, + }); + }); + it('should work with property initalizers', () => { const result = instance.boundProperty('bound property'); const expectedArgs = { diff --git a/src/decorators/dispatch.ts b/src/decorators/dispatch.ts index 6c0e38b..b0297fa 100644 --- a/src/decorators/dispatch.ts +++ b/src/decorators/dispatch.ts @@ -17,9 +17,11 @@ export function dispatch(): PropertyDecorator { const wrapped = function(this: any, ...args: any[]) { const result = originalMethod.apply(this, args); - const store = getBaseStore(this) || NgRedux.instance; - if (store) { - store.dispatch(result); + if (result !== false) { + const store = getBaseStore(this) || NgRedux.instance; + if (store) { + store.dispatch(result); + } } return result; };