From be5cb2f0b69eeb3ded05eec837cbee1e9db756c3 Mon Sep 17 00:00:00 2001 From: jarmit Date: Mon, 28 Feb 2022 12:33:00 -0800 Subject: [PATCH] Use catch instead of finally for browser compatibility (#161) --- src/mutator.ts | 10 ++++++---- test/mutatorTests.ts | 23 +++++++++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/src/mutator.ts b/src/mutator.ts index c342d31..8a0851f 100644 --- a/src/mutator.ts +++ b/src/mutator.ts @@ -1,5 +1,4 @@ import { action } from 'mobx'; - import ActionCreator from './interfaces/ActionCreator'; import ActionMessage from './interfaces/ActionMessage'; import MutatorFunction from './interfaces/MutatorFunction'; @@ -19,11 +18,14 @@ export default function mutator( // Wrap the callback in a MobX action so it can modify the store const actionType = getPrivateActionType(actionCreator); let wrappedTarget = action(actionType, (actionMessage: TAction) => { + const globalContext = getGlobalContext(); try { - getGlobalContext().currentMutator = actionType; + globalContext.currentMutator = actionType; target(actionMessage); - } finally { - getGlobalContext().currentMutator = null; + globalContext.currentMutator = null; + } catch (e) { + globalContext.currentMutator = null; + throw e; } }); diff --git a/test/mutatorTests.ts b/test/mutatorTests.ts index 8d3963c..c811b6e 100644 --- a/test/mutatorTests.ts +++ b/test/mutatorTests.ts @@ -80,4 +80,27 @@ describe('mutator', () => { // Assert expect(mockGlobalContext.currentMutator).toBe(null); }); + + it('sets the currentMutator back to null if error is thrown', () => { + // Arrange + let actionCreator: any = { + __SATCHELJS_ACTION_ID: 'testAction', + __SATCHELJS_ACTION_TYPE: 'testActionType', + }; + let callback: any = () => { + throw new Error('Error in Mutator'); + }; + mutator(actionCreator, callback); + + // Act + let subscribedCallback = (dispatcher.subscribe as jasmine.Spy).calls.argsFor(0)[1]; + try { + subscribedCallback(); + } catch { + // no op + } + + // Assert + expect(mockGlobalContext.currentMutator).toBe(null); + }); });