0

当我尝试在导入的函数上设置间谍时,我收到以下错误消息TypeError: Cannot read property '_isMockFunction' of undefined

我不明白这段代码有什么问题

导入的功能如下所示

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();
        });

    });
4

1 回答 1

1

根据您的代码中的Jest 文档https://facebook.github.io/jest/docs/en/jest-object.html#jestspyonobject-methodname

jest.spyOn(myFn, 'myInternalFn');

myFn需要是一个对象,并且myInternalFn需要是这个对象的一个​​属性。在当前的实现myInternalFn中隐藏在myFn范围内,而不是暴露在外部。我建议您重写代码(如果可能的话)以使用任一原型:

myFn.prototype.myInternalFn = function myInternalFn () { ... }

//and in tests
jest.spyOn(myFn.prototype, 'myInternalFn');

或直接分配给功能对象(对我来说不是最好的方法)

myFn.myInternalFn = function myInternalFn () { ... }

// and in tests
jest.spyOn(myFn, 'myInternalFn');

一个主要的想法是 - 如果不公开曝光myInternalFn,您就不能对其进行间谍活动。

于 2018-02-08T16:21:13.493 回答