How to expect one function to call another function?

后端 未结 1 894
庸人自扰
庸人自扰 2020-12-25 10:56

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 \'         


        
相关标签:
1条回答
  • 2020-12-25 11:14

    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:

    1. Modules that you import to myFunctions.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 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()
    }
    
    0 讨论(0)
提交回复
热议问题