sinonjs模仿依赖注入

时间:2014-03-18 03:02:04

标签: mocking javascript qunit sinon

我已将一些代码转换为库,并希望使用qunit和sinonjs对其进行单元测试

var modalDialogHandler = function( constructorOptions ){
    "use strict";

    var call = {};

    // --------------------------------------------------------------------------
    // attach modal dialogs to all links that are children of elements with this selector
    var enable = function( selector ) {
        jQuery( document ).on( 'click', selector, function( event ) {
            call.displayModalDialog(this);
            event.preventDefault();
            return false;
        });
    };

    var displayModalDialog = function(element) {}

    var inject = function (functionToReplace, injectedFunction) {
        call[functionToReplace] = injectedFunction;
        return injectedFunction;
    }

    call = {
        init: init,
        enable: enable,
        displayModalDialog: displayModalDialog,
        inject: inject
    };
    return call;
}

使用间谍来测试它的工作原理:

var m = new modalDialogHandler();
m.enable('.modal_dialog');

m.inject('displayModalDialog',this.spy());


jQuery('.modal_dialog').each( function (){
    this.click();
});
equal(m.displayModalDialog.callCount, 2,'successfully attached');

但是,我怎么能用嘲笑?我试图以这种方式注入模拟函数

var m = new modalDialogHandler();
var myAPI = { displayModalDialog: function () {} };
var mock = this.mock(myAPI);

var displayModalDialog = m.inject('displayModalDialog', myAPI.displayModalDialog);
mock.expects(displayModalDialog).twice();

jQuery('.modal_dialog').each( function (){
    this.click();
});
mock.verify();

我确定我需要嘲笑图书馆中更复杂的部分

0 个答案:

没有答案