这很奇怪。使用带有testem的jasmine2运行程序并执行以下规范(尽管它正确地标志着没有期望):
describe('Spying on array.prototype methods', function(){
it('should work this way', function(){
spyOn( Array.prototype, 'push' ).and.callThrough();
// expect(1).toBe(1);
});
});但是,添加一个expect (任何expect!)它导致堆栈溢出,在testem控制台中包含以下消息:RangeError: Maximum call stack size exceeded. at http://localhost:7357/testem/jasmine2.js, line 980,html报告页达到规范,然后挂起,而不显示任何实际结果。
最后,我想做这样的事情:
describe('Some structure.method', function(){
it('does not use native push', function(){
spyOn( Array.prototype, 'push' ).and.callThrough();
[].push(1); // actually more like `myStructure.myMethod('test')`
expect( Array.prototype.push ).not.toHaveBeenCalled();
});
});事先感谢任何人谁能揭示这个奇怪的。我能不窥探本地的典型方法吗?
发布于 2015-06-11 00:05:41
当您监视某物时,茉莉会创建一个包装器,以跟踪该函数的调用。在这里,当您监视prototype方法时,基本上甚至jasmine中的push操作本身都会调用间谍,而不是数组上的实际push方法,这会导致无限循环。
当您调用[].push(1)时,它实际上是打电话给追踪器,如下所示:
spy = function() {
callTracker.track({ //<-- Calls tracker to track invocation
object: this,
args: Array.prototype.slice.apply(arguments)
});这反过来将调用跟踪器和推送调用上下文调用到其内部跟踪器数组中,并进入递归循环,直到调用堆栈崩溃。
this.track = function(context) {
calls.push(context); //Now this again calls the spy
};相反,如果您监视数组实例上的方法,则不会出现此问题,因为它会为该数组实例的push属性创建一个间谍包装器(或者换句话说,该实例的push保存的引用(当前继承自数组原型)会被jasmine创建的间谍的新函数引用覆盖):示例:
it('does not use native push', function(){
var arr = [];
spyOn(arr, 'push' ).and.callThrough();
arr.push(1);
expect(arr.push).toHaveBeenCalledWith(1);
});但是作为一个真正的用例(至少我从来没有必要这样做),您可以始终检查目标数组的长度,并在特定的操作之后获得要与之比较的最后一项。您可能永远不需要监视本地方法(至少不需要数组: ),而是对感兴趣的对象进行测试,并监视这些目标方法。
https://stackoverflow.com/questions/30769204
复制相似问题