Skip to content

Commit

Permalink
Add proxy assignment to retain original expect methods
Browse files Browse the repository at this point in the history
  • Loading branch information
mattphillips committed Aug 7, 2018
1 parent fca515b commit 264a3c7
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
9 changes: 6 additions & 3 deletions src/withMessage.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@ class JestAssertionError extends Error {
}
}

export default expect => (actual, customMessage) => {
const matchers = expect(actual);

const wrapMatchers = (matchers, customMessage) => {
return Object.keys(matchers).reduce((acc, key) => {
const matcher = matchers[key];
const newMatcher = (...args) => {
Expand All @@ -31,3 +29,8 @@ export default expect => (actual, customMessage) => {
return Object.assign({}, acc, { [key]: newMatcher });
}, {});
};

export default expect => {
const expectProxy = (actual, customMessage) => wrapMatchers(expect(actual), customMessage); // partially apply expect to get all matchers and wrap them
return Object.assign(expectProxy, expect); // clone additional properties on expect
};
18 changes: 16 additions & 2 deletions src/withMessage.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,27 @@ import withMessage from './withMessage';
describe('withMessage()', () => {
const ACTUAL = 'ACTUAL';

test('does not remove additional methods from expect', () => {
expect.assertions(3);
const toBeMock = jest.fn();
const expectMock = jest.fn(() => ({ toBe: toBeMock }));
expectMock.extend = 'extend';

const newExpect = withMessage(expectMock);
newExpect(ACTUAL, 'should fail').toBe(1);
expect(newExpect.extend).toBe('extend');
expect(expectMock).toHaveBeenCalledWith(ACTUAL);
expect(toBeMock).toHaveBeenCalledWith(1);
});

test('does not throw when matcher passes', () => {
expect.assertions(1);
expect.assertions(2);
const toBeMock = jest.fn();
const expectMock = jest.fn(() => ({ toBe: toBeMock }));

withMessage(expectMock)(ACTUAL, 'should fail').toBe(1);
expect(1).toBe(1);
expect(expectMock).toHaveBeenCalledWith(ACTUAL);
expect(toBeMock).toHaveBeenCalledWith(1);
});

test.each([undefined, ''])('throws original error when given message: %s', message => {
Expand Down

0 comments on commit 264a3c7

Please sign in to comment.