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
, like import 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()
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…