Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one get the most recent call for a mock function in jest?

If I have a mock function say myMockFunction I know I can check its calls like so:

const firstCall = myMockFunction.mock.calls[0];

Is there an easy/clean way to get the most recent call?

I think that the following would work:

const mostRecentCall = myMockFunction.mock.calls[myMockFunction.mock.calls.length -1];

This seems rather hacky/tiresome, is there a cleaner/easier way?

like image 288
linuxdan Avatar asked Jul 18 '17 21:07

linuxdan


2 Answers

If calls is an array and you don't care to preserve its contents, you could do myMockFunction.mock.calls.pop() to get the last call.

like image 108
kristaps Avatar answered Nov 15 '22 00:11

kristaps


You should be able to access the last element by slicing backwards:

myMockFunction.mock.calls.slice(-1)[0]

Of course, if you don't have any calls yet, you'll get an undefined. Depending on your tests, that may or may not be an issue.

like image 30
Matthew D Avatar answered Nov 15 '22 00:11

Matthew D