How to expect one function to call another function?
Your approach does not work because you mock clearSomethingInModal
only in the context of your test file, so clearSomethingInModal
in the myFunctions.js
is still the original. The main point is that you can't mock something that is directly created in myFunctions.js
. The only thing that you can mock are:
- Modules that you import to
myFunctions.js
, likeimport clearSomethingInModal from 'clearSomethingInModal'
; - Callbacks that you pass into your function when calling them from your test;
This makes sense if you think about myFunctions.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 inside the box.
Here are two example that reflect the 2 points in the list:
myFunctions.test.js
import { resetModal } from '../myFunctions.js';
import clearSomethingInModal from 'clearSomethingInModal';
jest.mock('clearSomethingInModal', () => jest.fn())
describe('resetModal', () => {
it('calls the clearSomethingInModal function', () => {
resetCreationModal();
expect(clearSomethingInModal.mock.calls.length).toBe(1);
})
})
myFunctions.js
import clearSomethingInModal from 'clearSomethingInModal';
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()
}
Another way is to use done
and mock or spy on the implementation of the last function and check if the previous function was called by then.
it('should call function2 after function1', (done) => {
expect.assertions(2)
function2.mockImplementationOnce(() => {
expect(function1).toHaveBeenCalled()
done()
})
act() // This is where you run function you are testing
})
The drawback of this solution is that the structure of the test is not
// arrange
// act
// assert
but rather
// arrange & assert
// act