Search code examples
javascripttddjestjsspyon

How spy whether a function has been used or not with Jest unit testing for javascript?


When I try to set a spy on a imported function I get the following error msg TypeError: Cannot read property '_isMockFunction' of undefined

I don't understand what it's wrong with this code

Imported function is like below here export

export
function myFn(){
    let htmlEl = document.querySelector('html');
    let el = document.querySelector('.target-el');
    if(el){
        el.addEventListener('click', myInternalFn, false);
    }

    function myInternalFn () {
        isUserLoggedIn((isIn) => {
            let logoutClassName = 'el--logout';
            if (isIn) {
                el.classList.remove(logoutClassName);
                return;
            } 
            el.classList.add(logoutClassName);
        });
    }

    function isUserLoggedIn (fn) {
        return fn(localStorage.getItem('userLoggedIn') === 'true');
    }
}

document.addEventListener('DOMContentLoaded', () => {
    myFn();
});

TDD:

    import { betSlip } from "../src/main/javascript/custom/betslip-dialog";

    describe('Testing bet slip button (only on mobile)', function () {
         let htmlEl;
         let el;

         beforeEach(() => {
            document.body.innerHTML =
            `
            <html>
                <div class="target-el"></div>
            </html>
            `;

            myFn();
            htmlEl = document.querySelector('html');


        });

        it('When el button has been clicked for the first time', done => {
          jest.spyOn(myFn, 'myInternalFn');
          myInternalFn.click();
          expect(true).toBe(true);

          done();
        });

    });

Solution

  • According to Jest docs https://facebook.github.io/jest/docs/en/jest-object.html#jestspyonobject-methodname in your code

    jest.spyOn(myFn, 'myInternalFn');
    

    myFn needs to be an object and myInternalFn needs to be a property of this object. In current realization myInternalFn is hidden in myFnscope, and isn't exposed to outside. I suggest you to rewrite code (if it's possible) to use either prototype:

    myFn.prototype.myInternalFn = function myInternalFn () { ... }
    
    //and in tests
    jest.spyOn(myFn.prototype, 'myInternalFn');
    

    or direct assign to function object(not the best way as for me)

    myFn.myInternalFn = function myInternalFn () { ... }
    
    // and in tests
    jest.spyOn(myFn, 'myInternalFn');
    

    A main idea is - without public exposing myInternalFn you can't hang spy on it.