marchaos / jest-mock-extended

Type safe mocking extensions for Jest https://www.npmjs.com/package/jest-mock-extended
MIT License
828 stars 57 forks source link

Change name of calledWith method #39

Closed asnaseer-resilient closed 4 years ago

asnaseer-resilient commented 4 years ago

Hi,

I love this library and use it for all my tests. However, one thing has caught me and my colleagues out several times. It hinges around the calledWith matcher.

In the following code:

      mockServiceApi.updateService.calledWith(4, 2).mockResolvedValue(42);

We all continually mistake this to mean "expect this method to be called with parameters 4 and 2 and, if so, return a promise to 42".

We therefore continually think that this should fail with an error if the updateService method is called with some other parameters. This is because we are used to jest code where we say things like:

      expect(mockServiceApi.updateService).toHaveBeenCalledWith(4, 2);

which would throw an error if it wasn't called with those parameters.

I believe calledWith is actually saying "when this method is called with parameters 4 and 2 then return a promise to 42".

So, if it is called with some other parameters then it will not do the action of returning a promise to 42.

I think it would help if this was renamed to whenCalledWith. The code would then read:

      mockServiceApi.updateService.whenCalledWith(4, 2).mockResolvedValue(42);

This would make it explicit that its not an expectation that will throw. You could just introduce a new matcher named whenCalledWith that just forwards on to calledWith to keep your library backwards compatible.

What do you think?

marchaos commented 4 years ago

I personally prefer the brevity of calledWith and think that it's perfectly readable and understandable, but would be willing to change if there was enough community support behind it.