Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to have `toHaveBeenCalledWith` match a regular expression?

I have a function that appends a random number an then calls another function. I want to check that it was called with the text passed in and match any random number. I'd like to be able to pass a Regex without Jest literally matching the Regex. Something like:

 const typeFn = jest.fn();

 function type (text) {
     typeFn(text + Math.random());
 })


 type('hello')
 expect(typeFn).toHaveBeenCalledWith(/hello\d+/)
like image 578
Toli Avatar asked Sep 05 '18 20:09

Toli


1 Answers

You can use one of the helper functions in expect instead of an actual value:

expect(typeFn).toHaveBeenCalledWith(expect.stringMatching(/hello\d+/));

Here's a live example: https://repl.it/@marzelin/FrighteningCapitalConferences

like image 158
marzelin Avatar answered Oct 14 '22 15:10

marzelin