timkindberg / jest-when

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

Default wrongArgs implementation for README #91

Closed joebowbeer closed 2 years ago

joebowbeer commented 2 years ago

Thanks for creating this!

I'm familiar with this technique in sinon, and I find that verifying arguments at the call site often results in better tests than verifying them after execution.

In trying to replicate the patterns I've used in sinon, it wasn't clear from the README how to write the default failing function that handles the wrong-args case.

I include my implementation below in hopes that you include it or something similar in your README:

// A default implementation that fails
const wrongArgs = (...args: any[]) => {
  throw new Error(`Wrong args: ${JSON.stringify(args, null, 2)}`);
};

when(fn)
  .mockImplementation(wrongArgs)
  .calledWith(correctArgs)
  .mockReturnValue(expectedValue);
timkindberg commented 2 years ago

Thanks for the idea! That's pretty cool.

I'm starting to hate the README actually, it's getting very busy and hard to find things.

Also I'm starting to think the default behavior needs to be a more explicit abstraction, like maybe rename itwhen(fn).defaultImplementation() vs what it is today.

joebowbeer commented 1 year ago

by the way, I've replaced JSON.stringify with util.inspect in my current implementation of this function

// A default implementation that fails the test
export function wrongArgs(...args: any[]) {
  throw new Error(`Wrong args: ${inspect(args)}`)
}