timkindberg / jest-when

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

Feature request: calledWith() should accept RegEx when argument is a string #76

Closed FrenchMajesty closed 3 years ago

FrenchMajesty commented 3 years ago

Context:

I am trying to stub out calls to my database in my tests to return a specific object, this is what the code looks like:

const authToken = { /* ... */ };
 when(db.getById)
  .calledWith(`/users/${userId}/privateData/twitterToken`)
   .mockResolvedValue(authToken);

However I'm finding this a bit too rigid, as in some cases I don't have the userId since a fake user instance is used to authenticate. It requires me to do some weird manipulations in order to make the tests work. It would be neat if we could do something like this:

const authToken = { /* ... */ };
 when(db.getById)
  .calledWithRegEx(/privateData\/twitterToken/)
   .mockResolvedValue(authToken);

In this way, any calls to db.getById that matches my regex would receive the authToken mocked value, without having to be too granular/specific. This also applies really well when you have to provide a URL as a parameter, or some other long string literal that contains dynamic values.

timkindberg commented 3 years ago

This is already possible using expect.stringMatching(regex).

when(fn).calledWith(expect.stringMatching(/foo bar/))