Jimmy
Jimmy

Reputation: 3860

Jest: testing inner function is called

Given the below, how do I make sure that the inner foo function is called with the correct message when the bar function is executed? Thanks.

const foo = (message) => console.log(message);

const bar = () => foo('this is a message');

test('test that the foo function is called with the correct message when the bar' +
     ' function is executed', () => {
  bar();
  expect(foo).toHaveBeenCalledWith('this is a message');
});

Upvotes: 2

Views: 218

Answers (1)

kaxi1993
kaxi1993

Reputation: 4700

You need to mock foo function like this:

let foo = message => console.log(message)

const bar = () => foo('this is a message')

test('test that the foo function is called with the correct message when the bar function is executed', () => {
    foo = jest.fn()
    bar()
    expect(foo).toHaveBeenCalledWith('this is a message')
})

Upvotes: 2

Related Questions