问题描述
有什么区别
jasmine.createSpy('someMethod')
和
spyOn(someObject, 'someMethod')
为什么要选择使用 spyOn?
And why should one choose to use spyOn?
我的猜测是,第一个替代方案将匹配方法 someMethod,无论它包含在什么对象中,但 spyOn 仅在它包含在 someObject 中时才会匹配.从而使 createSpy 只是一个更通用的匹配器?
My guess is that the first alternative will match the method someMethod no matter in what object it's contained but spyOn will only match if it's contained in someObject. Thus making createSpy just a more generic matcher?
推荐答案
不同的是你应该在对象上有一个方法 spyOn
The difference is that you should have a method on the object with spyOn
const o = { some(): { console.log('spied') } };
spyOn(o, 'some');
使用 createSpy()
为您创建模拟方法时:
while the mock method is created for your with createSpy()
:
const o = {};
o.some = jasmine.createSpy('some');
spyOn
的好处是可以调用原方法:
The advantage of the spyOn
is that you can call the original method:
spyOn(o, 'some').and.callThrough();
o.some(); // logs 'spied'
正如@estus 所说,在 spyOn
的情况下测试后会恢复原始方法.这应该在重新分配时手动完成.
And as @estus says the original method is restored after the test in case of spyOn
. This should be done manually when it's reassigned with.
这篇关于为什么使用 spyOn 而不是 jasmine.createSpy?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!