簡體   English   中英

試圖對Array.prototype方法進行間諜監視(Jasmine)會導致堆棧溢出

[英]Trying to spy (Jasmine) on Array.prototype methods causes stack overflow

這很奇怪。 testemjasmine2配合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 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();
  });
});

在此先感謝任何可以闡明這種奇怪之處的人。 我可以不監視本機原型方法嗎?

當您監視某些東西時,茉莉花會創建一個包裝器,以跟蹤該函數的調用。 在這里,當您監視原型方法時,基本上甚至茉莉花本身中的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的那實例被jasmine創建的間諜的新函數引用覆蓋:示例:

it('does not use native push', function(){
  var arr = [];
  spyOn(arr, 'push' ).and.callThrough();
  arr.push(1);
  expect(arr.push).toHaveBeenCalledWith(1);
});

但是作為一個實際用例(至少我從來沒有用過),您始終可以檢查目標數組的長度,並在進行特定操作后獲取要比較的最后一項。 您可能永遠不需要監視本機方法(至少不是數組:)),而是針對自己感興趣的對象進行測試並監視那些目標方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM