javascript - Test the context of a method call using sinonjs -
I have a class where I initially compose a method -
< Code> function MyClass () {this.onHttpCallback = _.bind (onHttpCallback, this); } function onHttpCallback () {// ...}If call to
onHttpCallback , then always with reference to MyClass's object Is called? I'm using sinon.js to counterfeit and the following code does not work -
it should be "bind", function () { // ctrl MyClass var dummy_obj = {}; var spy = sinon.spy (ctrl.onHttpCallback) is a purpose; spy.call (dummy_obj); spy.always callon (ctrl). should.be.ok;}); According to the comments in the following reply, it appears that it is impossible to test the bond for any method.
Update
Go to my problem
// Source.js function MyClass () {} MyClass.prototype.init = function () {this .onHttpCallback = _.bind (MyClass.onHttpCallback, this); } MyClass.onHttpCallback () {// ...} //Test.js (It should be bound to 'http callback', function) (sinon.spy (_, 'bind'); ctrl.init (); _ .bind .calledWith (ctrl.constructor.onHttpCallback, ctrl). should.be.ok; _.bind.restore ();});
Works like a charm!
this change however you explicitly
MyClass , because you use the
call with
dummy_obj detective.
The detective wraps the original function, so there is no concept of binding that function in it. It will still accept different binding on the wrapper function, then try calling the original code from thatthis , which is ignored by the original function.
var reference = {foo: 'bar'}; var origin = _.bind (function () {console.log (this);}, context); Var detective = function (original) {var spyFn = function () {var _this = this; spyFn.calledOn = function (ctx) {return ctx === _this; }; Original return (This, argument); }; Return detective FN; }; var originalSpy = Detective (Original); // will call spyFn with a different `this`, but the original binding will not affect originalSpy.call ({anything: 'else'}); & Gt; & Gt; {Foo: 'bar'} // Since the detective can not know the original binding, it seems that the assumption is wrong. OriginalSpy.calledOn (context) === Wrong;
Comments
Post a Comment