matt-p matt-p - 13 days ago 5
Javascript Question

Jest - mocking a function call

I am trying to mock a function call, and expect it to have called another function within it once.

myFunctions.test.js

import { resetModal } from '../myFunctions.js';

describe('resetModal', () => {
it('calls the clearSomethingInModal function', () => {
const clearSomethingInModal = jest.fn();
resetCreationModal();
expect(clearSomethingInModal.mock.calls.length).toBe(1);
})
})


myFunctions.js

export resetModal() {
clearSomethingInModal()
}


However, Jest output says that it has not been called. If anyone can suggest how best to do this, I would be very grateful.

Answer

Your approach dose not work cause you mock clearSomethingInModal only in the context of your test file, so clearSomethingInModal in the myFunction.js is still the original. The main point is that you can't mock something that is directly created in myFunction.js. The only thing that you can mock are

  1. modules that you import to myFunction.js, like import clearSomethingInModal from 'clearSomethingInModal'
  2. callbacks that you pass into your function when calling them from your test

This makes sense if you thing about myFunction.js as a blackbox, where you can control what goes in, like imports or function arguments, and where you can test what comes out. But you can not test the stuff that happens in between.

Here are two example that reflect the 2 points in the list

myFunctions.test.js

import { resetModal } from '../myFunctions.js';
import clearSomethingInModalfrom 'clearSomethingInModal';

jest.mock('clearSomethingInModal', ()=> jest.fn())

describe('resetModal', () => {
  it('calls the clearSomethingInModal function', () => {
    resetCreationModal();
    expect(clearSomethingInModal.mock.calls.length).toBe(1);
  })
})

myFunctions.js

export resetModal() {
  clearSomethingInModal()
}

myFunctions.test.js

import { resetModal } from '../myFunctions.js';

describe('resetModal', () => {
  it('calls the clearSomethingInModal function', () => {
    const clearSomethingInModal = jest.fn();
    resetCreationModal(clearSomethingInModal);
    expect(clearSomethingInModal.mock.calls.length).toBe(1);
  })
})

myFunctions.js

export resetModal(clearSomethingInModal) {
  clearSomethingInModal()
}