timkindberg / jest-when

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

support given syntax in addition to when #43

Closed jeyj0 closed 4 years ago

jeyj0 commented 4 years ago

I like to follow the test pattern of given, when, then. This pattern makes using a syntax using when unintuitive in the given block (which is where this library would be used).

I have created aliases for the supported functionality in a fork, which look like this:

given(..).calledWith(..).returns             === when(..).calledWith(..).mockReturnValue
given(..).calledWith(..).onceReturns         === when(..).calledWith(..).mockReturnValueOnce
given(..).calledWith(..).resolvesTo          === when(..).calledWith(..).mockResolvedValue
given(..).calledWith(..).onceResolvesTo      === when(..).calledWith(..).mockResolvedValueOnce
given(..).calledWith(..).rejectsWith         === when(..).calledWith(..).mockRejectedValue
given(..).calledWith(..).onceRejectsWith     === when(..).calledWith(..).mockRejectedValueOnce
given(..).calledWith(..).isImplementedAs     === when(..).calledWith(..).mockImplementation
given(..).calledWith(..).onceIsImplementedAs === when(..).calledWith(..).mockImplementationOnce

This works with expectCalledWith too, of course.

The exports WhenMock, verifyAllWhenMocksCalled and resetAllWhenMocks are aliased to GivenMock, verifyAllGivenMocksCalled and resetAllGivenMocks respectively.

It would also "fix" the linguistic problems #24 mentions by allowing given(..).returns(..).

In my implementation the two syntaxes can be combined in any way, which allows for calls like given(..).calledWith(..).mockReturnValue(..). However, it should be relatively simply to disallow this, and I'd be happy to do so.

Is this something you'd be interested in supporting?

jeyj0 commented 4 years ago

This is the commit that implements this.

timkindberg commented 4 years ago

Responded to PR