Jest Difference Between toBeCalledWith and toHaveBeenCalledWith

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”

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)