Skip to content

Commit

Permalink
patch: add error handling to runWithContext (#164)
Browse files Browse the repository at this point in the history
  • Loading branch information
ealush committed May 27, 2020
1 parent ed58c37 commit 2dd93ae
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
9 changes: 8 additions & 1 deletion packages/vest/src/lib/runWithContext/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,16 @@ import Context from '../../core/Context';
const runWithContext = (ctxRef, fn) => {
const context = new Context(ctxRef);

const res = fn(context);
let res;

try {
res = fn(context);
} catch {
/* */
}

Context.clear();

return res;
};

Expand Down
33 changes: 33 additions & 0 deletions packages/vest/src/lib/runWithContext/spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ describe('runWithContext', () => {
runWithContext(parent, fn);
expect(fn).toHaveBeenCalledTimes(1);
});

it('Should clear context after running callback', () => {
const fn = jest.fn(context => {
expect(singleton.useContext()).toMatchObject(context);
Expand All @@ -62,4 +63,36 @@ describe('runWithContext', () => {
expect(mockContext).toHaveBeenCalledWith(parent);
});
});

describe('When an error is thrown inside the callback', () => {
let cb;

beforeEach(() => {
cb = jest.fn(() => {
throw new Error();
});
});

test('sanity', () => {
expect(() => cb()).toThrow();
});

it('Should catch error', () => {
expect(() => {
runWithContext({}, cb);
}).not.toThrow();

expect(cb).toHaveBeenCalled();
});

it('Should clear the context', () => {
const context = { [faker.random.word()]: faker.random.word() };

runWithContext(context, () => {
expect(singleton.useContext()).toMatchObject(context);
throw new Error();
});
expect(singleton.useContext()).toBeNull();
});
});
});

0 comments on commit 2dd93ae

Please sign in to comment.