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

Viewed 5937

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?

4 Answers

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.

As mentioned in the jest documentation, https://jestjs.io/docs/en/mock-functions

// The last call to the mock function was called with the specified args
expect(mockFunc.mock.calls[mockFunc.mock.calls.length - 1]).toEqual([
  arg1,
  arg2,
]);

Usage of pop alters the the mock.calls array

Related