.toHaveBeenCalled()

Also under the alias: .toBeCalled()

Use .toHaveBeenCalled to ensure that a mock function got called.

For example, let's say you have a drinkAll(drink, flavor) function that takes a drink function and applies it to all available beverages. You might want to check that drink gets called for 'lemon', but not for 'octopus', because 'octopus' flavor is really weird and why would anything be octopus-flavored? You can do that with this test suite:

  1. describe('drinkAll', () => {
  2. test('drinks something lemon-flavored', () => {
  3. const drink = jest.fn();
  4. drinkAll(drink, 'lemon');
  5. expect(drink).toHaveBeenCalled();
  6. });
  7. test('does not drink something octopus-flavored', () => {
  8. const drink = jest.fn();
  9. drinkAll(drink, 'octopus');
  10. expect(drink).not.toHaveBeenCalled();
  11. });
  12. });