理解 Sinon Spies:当调用一个 spy-wrapped 方法时会发生什么?
Understanding Sinon Spies: What happens when a spy-wrapped method is called?
当我像这样将 class 的方法包装到 Sinon-spy 中时:
sinon.spy(myObject, "myMethod")
间谍内部发生了什么?
我猜间谍对象有一个指向 "myObject.myMethod" 的引用。
当方法变成调用时会发生什么?
我知道间谍会记录有关调用的信息,例如调用时间、使用的参数等。
但是 myMethod 真的 被调用了吗?
我的意思是:通过间谍对象进一步调用? 间谍对象作为代理吗?还是只记录信息?
从简单的测试来看,sinon spy 似乎确实调用了原始方法:
it('does a thing', function() {
const el = {};
el.thing = function() { console.log('thing'); }
sinon.spy(el, 'thing');
el.thing();
console.log(el.thing.called);
});
// prints:
// thing
// true
从the docs看来也是这样:
sinon.spy(object, "method") creates a spy that wraps the existing function object.method. The spy will behave exactly like the original method (including when used as a constructor), but you will have access to data about all calls.
当我像这样将 class 的方法包装到 Sinon-spy 中时:
sinon.spy(myObject, "myMethod")
间谍内部发生了什么?
我猜间谍对象有一个指向 "myObject.myMethod" 的引用。
当方法变成调用时会发生什么?
我知道间谍会记录有关调用的信息,例如调用时间、使用的参数等。
但是 myMethod 真的 被调用了吗?
我的意思是:通过间谍对象进一步调用? 间谍对象作为代理吗?还是只记录信息?
从简单的测试来看,sinon spy 似乎确实调用了原始方法:
it('does a thing', function() {
const el = {};
el.thing = function() { console.log('thing'); }
sinon.spy(el, 'thing');
el.thing();
console.log(el.thing.called);
});
// prints:
// thing
// true
从the docs看来也是这样:
sinon.spy(object, "method") creates a spy that wraps the existing function object.method. The spy will behave exactly like the original method (including when used as a constructor), but you will have access to data about all calls.