【问题标题】:How spy whether a function has been used or not with Jest unit testing for javascript?如何通过 Jest javascript 单元测试来监视一个函数是否已被使用?
【发布时间】:2018-02-09 00:21:13
【问题描述】:

当我尝试在导入的函数上设置间谍时,我收到以下错误消息 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();
        });

    });

【问题讨论】:

    标签: javascript tdd jestjs spyon


    【解决方案1】:

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

    jest.spyOn(myFn, 'myInternalFn');
    

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

    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 你不能挂在它上面。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-07
      • 1970-01-01
      • 2010-12-19
      • 1970-01-01
      • 2020-05-22
      • 2021-04-12
      • 2017-09-18
      相关资源
      最近更新 更多