HMR
HMR

Reputation: 39250

jest mock function will not be called but console.log proves it is called

I have the following function I would like to test:

export const addLine = async (component) => {
  if (!component.cartExists) {
    await component.createMyCart(1);
  }
  console.log('updateMyCart',component.updateMyCart)
  return component.updateMyCart(2)
}

This is my test:

it('channels added to cart line item', () => {
  const updateMyCart = jest.fn();
  const createMyCart = jest.fn();
  const component = { cartExists:false, updateMyCart, createMyCart };
  createMyCart.mockReturnValue(Promise.resolve(88))
  addLine(component);
  expect(createMyCart).toHaveBeenCalledWith(1)
  expect(updateMyCart)
    .toHaveBeenCalledWith(2)
});

It shows the console.log in the function that is tested:

  ● Console

    console.log src/components/common/shared.js:155
      updateMyCart function mockConstructor() {
              return fn.apply(this, arguments);
            }

expect(jest.fn()).toHaveBeenCalledWith(...expected)

Expected: 2

Number of calls: 0

  89 |     expect(createMyCart).toHaveBeenCalledWith(1)
  90 |     expect(updateMyCart)
> 91 |       .toHaveBeenCalledWith(2)
     |        ^
  92 |     
  93 |   });
  94 | 

The test will pass if I set cartExist to true and skip testing createMyCart was called:

const component = { cartExists:true, updateMyCart, createMyCart };

createMyCart.mockReturnValue(Promise.resolve(88))
addLine(component);
// expect(createMyCart).toHaveBeenCalledWith(1)
expect(updateMyCart)
  .toHaveBeenCalledWith(2)

It also passes when I remove the await in await component.createMyCart(1); but cartExists is false

Upvotes: 1

Views: 870

Answers (1)

HMR
HMR

Reputation: 39250

As in comment, I missed waiting for addLine to finish: await addLine(component) and it('channels added to cart line item', async () => { solved it

Upvotes: 1

Related Questions