本文介绍了为什么使用spyOn而不是jasmine.createSpy?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别

为什么要选择使用spyOn?

And why should one choose to use spyOn?

我的猜测是,第一个替代方法将匹配someMethod方法,无论它包含在哪个对象中,但spyOn只会匹配someObject中包含的对象。这样makeSpy只是一个更通用的匹配器?

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()

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 11:44