简体   繁体   中英

Using sinon.js spy() to wrap an existing function

I'm new to JavaScript testing and have run across a problem when trying to use sinon.js to spy on existing functions.

Let's say I have a function called

nsClientInfectionControlIndex.handleEditButton();

which looks like

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." );
    }
},

};

Now in my test.js I used the following code

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

//Act
nsClientInfectionControlIndex.handleEditButton();

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

And the test fails (returns a false) although I would expect a true because the nsClientInfectionControlIndex.showQtipError is called.

Although as far as I understand the Sinon documentation I'm spying on my function correctly by including the function in the constructor. http://sinonjs.org/docs/#sinonspy

I can get it to work correctly if I approach the spy this way,

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

//Act
nsClientInfectionControlIndex.handleEditButton();

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

However this replaces the original method functionality. Am I approaching this incorrectly? Any help would be appreciated.

When spying on object functions you must provide the object and function name separately rather than the actual function. This allows Sinon to replace the real function with the spy.

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

Warning: If any code stores the function into a variable before setting up the spy, it will bypass the spy.

// before test runs
var callback = nsClientInfectionControlIndex.showQtipError;

// in test
var errorSpy = ...

// activated by test
callback();  <-- bypasses spy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM