Skip to content

Commit

Permalink
Support function matchers
Browse files Browse the repository at this point in the history
  • Loading branch information
timkindberg committed Feb 7, 2021
1 parent d4b7e18 commit 6190463
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/when.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,17 @@ const checkArgumentMatchers = (expectCall, args) => (match, matcher, i) => {

// Assert the match for better messaging during a failure
if (expectCall) {
expect(arg).toEqual(matcher)
if (typeof matcher === 'function') {
const isMatch = matcher(arg)
const msg = `Failed function matcher within expectCalledWith: ${matcher.name}(${JSON.stringify(arg)}) did not return true\n\n\n...rest of the stack...`
assert.equal(isMatch, true, msg)
} else {
expect(arg).toEqual(matcher)
}
}

if (typeof matcher === 'function') {
return matcher(arg)
}

return utils.equals(arg, matcher)
Expand Down
30 changes: 30 additions & 0 deletions src/when.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,36 @@ describe('When', () => {
expect(fn(1, 'foo', true, 'whatever', undefined, 'oops')).toEqual(undefined)
})

it('works with custom function args', () => {
const fn = jest.fn()

const allValuesTrue = (arg) => Object.values(arg).every(Boolean)
const numberDivisibleBy3 = (arg) => arg % 3 === 0

when(fn)
.calledWith(allValuesTrue, numberDivisibleBy3)
.mockReturnValue('x')

expect(fn({ foo: true, bar: true }, 9)).toEqual('x')
expect(fn({ foo: true, bar: false }, 9)).toEqual(undefined)
expect(fn({ foo: true, bar: false }, 13)).toEqual(undefined)
})

it('expects with custom function args', () => {
const fn = jest.fn()

const allValuesTrue = (arg) => Object.values(arg).every(Boolean)
const numberDivisibleBy3 = (arg) => arg % 3 === 0

when(fn)
.expectCalledWith(allValuesTrue, numberDivisibleBy3)
.mockReturnValue('x')

expect(fn({ foo: true, bar: true }, 9)).toEqual('x')
expect(() => fn({ foo: false, bar: true }, 9)).toThrow(/Failed function matcher within expectCalledWith: allValuesTrue\(\{"foo":false,"bar":true\}\) did not return true/)
expect(() => fn({ foo: true, bar: true }, 13)).toThrow(/Failed function matcher within expectCalledWith: numberDivisibleBy3\(13\) did not return true/)
})

it('supports compound when declarations', () => {
const fn = jest.fn()

Expand Down

0 comments on commit 6190463

Please sign in to comment.