timkindberg / jest-when

Jest support for mock argument-matched return values.
MIT License
737 stars 39 forks source link

`.calledWithContaining(...)` #105

Open wh1t3cAt1k opened 1 year ago

wh1t3cAt1k commented 1 year ago

That would expect a Partial of each of the arguments and apply expect.objectContaining matcher internally to each of the passed arguments.

How it is useful

Imagine method A receiving an object { x: number, y: number, z: number } as a parameter and delegating to method B which wants an {x: number, y: number }. To avoid extra memory allocations (our app is sensitive to that), we pass the object as-is since it satisfies the reduced shape expected by method B.

However, .calledWith fails because there is an extra unexpected property.

Workaround:

timkindberg commented 1 year ago

You can also achieve this using the allArgs helper.

Maybe something like this:

const fn = jest.fn()
const objectContaining = (obj) => when.allArgs((args, equals) => equals(args[0], expect.objectContaining(obj)))

when(fn)
  .calledWith(objectContaining({ x: 1, y: 1 }))
  .mockReturnValue('success')