timkindberg / jest-when

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

Feature Request: create spy #61

Closed joeyjiron06 closed 3 years ago

joeyjiron06 commented 3 years ago

Thanks for the amazing library! This is exactly what I have been looking for and I hope something like this gets added to the jest core codebase soon.

I have a lot of boilerplate code that I would like to reduce and I think with a small modification to this library I can make that happen. I often mock libraries that I use in my codebase to mock the return values from the library. For instance, in my code I might use an Azure sdk and write tests that will mock the return value of the SDK and test how my code behaves. It's possible to mock those classes easily with this library, but the code is a bit hard to read so cleaning it up would be nice.

current

when(jest.spyOn(MetricsAdvisorClient.prototype, 'listAnomalies'))
  .calledWith(1)
  .mockReturnValue(123);

when(jest.spyOn(MetricsAdvisorClient.prototype, 'listAnomalies'))
  .calledWith(2)
  .mockReturnValue(456);

Would you consider a PR for the when function to accept a second argument so I can do something like this:

when(MetricsAdvisorClient.prototype, 'listAnomalies')
  .calledWith(1)
  .mockReturnValue(123);

when(MetricsAdvisorClient.prototype, 'listAnomalies')
  .calledWith(2)
  .mockReturnValue(456);

Internally, the when function would call jest.spyOn when it sees 2 arguments and then return the when object as usual. I realize this example is trivial, but i sometimes have 3 different functions that im mocking and I think the code looks much cleaner with the second approach.

Another approach could be to export a new "when" function with a different name that calls jest.spyOn internally.

Let me know what you think.

Keep up the great work!

timkindberg commented 3 years ago

I think I'd prefer to keep the jest.spyOn explicit, just like we currently require jest.fn to be explicit. Sorry 😬 but thanks for the suggestion!