2014-12-15 15 views
5

Diciamo che hanno i seguenti metodi:stubbing un metodo prototipo con Sinon

Controller.prototype.refresh = function() { 
    console.log('refreshing'); 
} 

Controller.prototype.delete = function (object) { 
    var self = this; 
    object.delete({id: object.id}, function() { 
    self.refresh(); 
    }); 
} 

ora nella mia (moka) prova:

beforeEach(function() { 
    var controller = new Controller(); 
    var proto = controller.__proto__; 
    var object = {id: 1, delete: function (options, callback) { callback(); }; 
    sinon.stub(proto, 'refresh', function {console.log('refreshing stub')}); 
    controller.delete(object); 
}); 

it('doesnt work', function() { 
    expect(object.delete.callCount).to.equal(1); 
    expect(proto.refresh.callCount).to.equal(1); 
}); 

Questo, tuttavia, stampe "rinfrescante" per la console . C'è un modo di usare sinon per stubare un prototipo live?

+0

ha funzionato per me: http://jsfiddle.net/b36u47jq/. La riga di codice 'var object =' declaration/definition manca una parentesi graffa - potrebbe essere questo il problema? – psquared

risposta

3

Ecco come lo farei:

describe('test', function() { 
    before(function() { 
    // stub the prototype's `refresh` method 
    sinon.stub(Controller.prototype, 'refresh'); 
    this.object = { 
     id: 1, 
     delete: function (options, callback) { callback(); } 
    }; 
    // spy on the object's `delete` method 
    sinon.spy(this.object, 'delete'); 
    }); 

    beforeEach(function() { 
    // do your thing ... 
    this.controller = new Controller(); 
    this.controller.delete(this.object); 
    }); 

    after(function() { 
    // restore stubs/spies after I'm done 
    Controller.prototype.refresh.restore(); 
    this.object.delete.restore(); 
    }); 

    it('doesnt work', function() { 
    expect(this.object.delete.callCount).to.equal(1); 
    expect(this.controller.refresh.callCount).to.equal(1); 
    }); 
}); 
Problemi correlati