编程语言
首页 > 编程语言> > javascript – 如何使用sinon.js模拟/存根回调函数?

javascript – 如何使用sinon.js模拟/存根回调函数?

作者:互联网

我想用QUnit和Sinon.Js编写单元测试.我有一个应用程序,用户可以点击按钮和模式对话框来处理下载一些文件.用户可以关闭对话框,它会触发一个方法来运行以重置某些变量.我的测试代码:

$(function() {
    $.fn.copy_button = function(){};

    ln_download_view = new DownloadModalView();
    ln_download_view.modal = {'modal': function() {}};
    var download_modal_dialog = $('.download-modal');
    download_modal_dialog.modal = function(param){};
    var modal_mock = sinon.mock(ln_download_view.modal);
    var download_modal_dialog_mock = sinon.mock(download_modal_dialog);

    //Should be inserted, because ln_download_view.modal is mocked
    //The close button even handler
    $('#btn_close_modal').click(function(){
        download_modal_dialog.modal('hide');
    });

    //Dirty stuff to do after the window closes
    //Basicly the click triggers this event handler
    $('.download-modal').on('hide',function() {
        window.clearInterval(window.periodicalTimer);
    });

    $('div .option-container').click(function() {
        if(!$(this).hasClass("selected-option"))
        {
            $('div #option-presenting').toggleClass("selected-option");
            $('div #option-editing-and-presenting').toggleClass("selected-option");

            $('.image').toggle();
        }
    });

    module("views");
    test("Download modal dialog is displayed", function(){
        var modal_triggered = modal_mock.expects("modal").once();
        ln_download_view.handleDownloadClick();
        ok(modal_triggered.verify());
    });

    test("Download modal dialog is closed",function(){
        var modal_triggered = download_modal_dialog_mock.expects("modal");
        $('#btn_close_modal').trigger('click');
        ok(modal_triggered.verify());
    });
});

我不明白的是,我如何测试/模拟/存储这段代码:

$('.download-modal').on('hide',function() {
    window.clearInterval(window.periodicalTimer);
});

我还没有深刻的理解.

解决方法:

你不能模拟/存根匿名函数.但是你可以进行重构和存根/模拟命名回调.

$('.download-modal').on('hide', onHide);

var onHide = function() {
    window.clearInterval(window.periodicalTimer);
};

// ...

sinon.stub(onHide);

标签:qunit,javascript,sinon
来源: https://codeday.me/bug/20190728/1566217.html