I'm using $.proxy(this, 'methodName') to use methods of my object as event handlers for DOM events.

When it comes to testing I'd like to use Jasmine's spyOn to monitor whether the callbacks get fired. However as the listener is attached within my Object's constructor by the time I get to spying on the method it's too late, and the raw, unspied function has already been used by $.proxy.

What are good approaches to tackling this? One thing I've considered is spying on the prototype's methods directly, but I'm worried about the impact this might have on each test being independent of others. Another would be to change how I attach the listeners in my code, but this seems like throwing out the baby with the bathwater.

有帮助吗?

解决方案

You can spy on the prototype of object before the test starts. So it will not have any impact of your other tests.

var function A {
  $.proxy(this, 'methodName');
}

a.prototype.methodName = function() {
  console.log('test');
}

describe('…', function() {
  var a;
  before(function() {
    jasmine.spyOn(a.prototype, 'methodName');
    a = new A();
  });

  it('should…', function() { 

  });

});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top