首页 文章

使用sinon.js spy()来包装现有函数

提问于
浏览
1

我是JavaScript测试的新手,在尝试使用sinon.js监视现有函数时遇到了一个问题 .

假设我有一个叫做的函数

nsClientInfectionControlIndex.handleEditButton();

看起来像

var nsClientInfectionControlIndex = {

showQtipError : function (message)
{
    ///<summary>Shows qTip error on edit button</summary>
    ///<param name="message">The text message to be displayed</param>
    $( "#editBtn" ).qtip( nsCBS.ErrorTip( message  ) ).qtip( "show" );
},

goToEditPage : function (id)
{
    ///     <summary>Navigates browser window to edit page</summary>
    ///     <param name="id">The data-id (Client Infection Control Id) attribute from selected row</param>
    var url = '/ClientInfectionControl/ClientInfectionControl/'
    window.location.href = url + "?id=" + id;
},

handleEditButton: function () {
    var id = $( ".selectedRow" ).attr( "data-id" );
    if ( id != null ) {
        nsClientInfectionControlIndex.goToEditPage( id );
    } else {
        nsClientInfectionControlIndex.showQtipError( "Please select a Client Infection Control Note first." );
    }
},

};

现在在我的test.js中我使用了以下代码

var errorSpy = sinon.spy( nsClientInfectionControlIndex.showQtipError );

//Act
nsClientInfectionControlIndex.handleEditButton();

//Assert
equal( errorSpy.called, true, "test" );

并且测试失败(返回false)虽然我期望为true,因为调用了nsClientInfectionControlIndex.showQtipError .

虽然据我所知,Sinon文档通过在构造函数中包含函数来正确地监视我的函数 . http://sinonjs.org/docs/#sinonspy

如果我以这种方式接近 Spy ,我可以让它正常工作,

var errorSpy = sinon.spy();
nsClientInfectionControlIndex.showQtipError = errorSpy;

//Act
nsClientInfectionControlIndex.handleEditButton();

//Assert
equal( errorSpy.called, true, "test" );

但是,这取代了原始方法功能 . 我接近这个错误吗?任何帮助,将不胜感激 .

1 回答

  • 3

    在监视对象函数时,必须单独提供对象和函数名称而不是实际函数 . 这允许Sinon用 Spy 取代真正的功能 .

    var errorSpy = sinon.spy( nsClientInfectionControlIndex, "showQtipError" );
    

    Warning: 如果任何代码在设置 Spy 之前将函数存储到变量中,它将绕过 Spy .

    // before test runs
    var callback = nsClientInfectionControlIndex.showQtipError;
    
    // in test
    var errorSpy = ...
    
    // activated by test
    callback();  <-- bypasses spy
    

相关问题