2016-11-19 98 views
0

如果在回調函數中調用該方法,則在對象上使用spyOn似乎會失敗。茉莉花不會注意到任何回調中的方法調用。Jasmine spyOn函數在回調函數中不起作用

請參閱下面的代碼,我在child.print()方法上創建了一個間諜。如果我在回調(的setTimeout)調用child.print(),它不工作:

it('test', function() { 
    const child = { 
     print: function() { 
      console.log('child'); 
     } 
    }; 
    spyOn(child, 'print'); 
    const parent = { 
     callChildInCallback: function() { 
      setTimeout(()=> child.print(), 1000); 
     } 
    }; 
    parent.callChildInCallback(); 
    expect(child.print.calls.count()).toEqual(1); 
}); 

這人會失敗,出現錯誤「預計0至1等於」

但是如果我直接調用它,它的工作原理:

it('test', function() { 
    const child = { 
     print: function() { 
      console.log('child'); 
     } 
    }; 
    spyOn(child, 'print'); 
    const parent = { 
     callChild: function() { 
      child.print(); 
     } 
    }; 
    parent.callChild(); 
    expect(child.print.calls.count()).toEqual(1); 
}); 

我試圖斷點設置步入回調,似乎圍繞我們正在測試是走功能的間諜包,這是該表面上的原因。有人可以解釋爲什麼會發生這種情況,以及正確的方法嗎?

感謝您的閱讀〜

回答

1

你需要使用茉莉花clock與超時功能工作

it('test', function() { 
jasmine.clock().install(); 
    const child = { 
    print: function() { 
     console.log('child'); 
    } 
    }; 
    spyOn(child, 'print').and.callThrough(); 
    const parent = { 
    callChildInCallback: function() { 
     setTimeout(function() { 
     child.print() 
     }, 1000); 
    } 
    }; 
    parent.callChildInCallback(); 
    jasmine.clock().tick(1001); 
    expect(child.print.calls.count()).toEqual(1); 
});