Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest Difference Between toBeCalledWith and toHaveBeenCalledWith

Tags:

jestjs

This isn't obvious from the docs but... What is the difference between toBeCalledWith and toHaveBeenCalledWith?

like image 673
Exitos Avatar asked Sep 05 '19 07:09

Exitos


Video Answer


1 Answers

From the docs https://jestjs.io/docs/en/expect#tohavebeencalledwitharg1-arg2-

.toHaveBeenCalledWith(arg1, arg2, ...) under the alias: .toBeCalledWith()

From the source code:

https://github.com/facebook/jest/blob/b7cb5221bb06b6fe63c1a5e725ddbc1aaa82d306/packages/expect/src/spyMatchers.ts#L1128

https://github.com/facebook/jest/blob/b7cb5221bb06b6fe63c1a5e725ddbc1aaa82d306/packages/expect/src/spyMatchers.ts#L1131

//...
  toBeCalledWith: createToBeCalledWithMatcher('toBeCalledWith'),
  toHaveBeenCalled: createToBeCalledMatcher('toHaveBeenCalled'),
  toHaveBeenCalledTimes: createToBeCalledTimesMatcher('toHaveBeenCalledTimes'),
  toHaveBeenCalledWith: createToBeCalledWithMatcher('toHaveBeenCalledWith'),
//...

They are created by the createToBeCalledWithMatcher function with only a different name.

So, they are the same.

UPDATE: Here is my personal understanding of why jestjs provide these matcher APIs aliases.

jestjs builds on jasmine test runner, see Jasmine and Test Assertion Improvements

jasmine only provides a matcher - toHaveBeenCalledWith.

jestjs provides better matcher APIs over jasmine, The toBeCalledWith alias is shorter, easier to remember, and easier to use. There doesn't seem to be much semantic need for "have been"

like image 117
slideshowp2 Avatar answered Sep 28 '22 10:09

slideshowp2