[英]Using Jasmine how to check if a local method has been called?
我正在嘗試測試是否從另一個方法( method2 )調用本地方法( method1 )。 我嘗試了類似的方法,但是由於method1()仍然具有原始定義,因此它不起作用。 該代碼段如下所示:
var ClassA = function () {
var method1 = function () {
console.log('method1');
};
var method2 = function () {
method1();
};
return {method1: method1, method2: method2}
}
測試用例:
it("should call method1 when method2 is called", function () {
var objectA = new ClassA();
spyOn(objectA, 'method1').andCallThrough;
objectA.method2();
expect(objectA, 'method1').toHaveBeenCalled();
});
嘗試覆蓋方法1沒有成功:
objectA.method1 = jasmine.createSpy('aSpy').andCallThrough();
當您調用new ClassA()時,您將調用ClassA函數並獲得具有相關原型的新對象。 這意味着當您spyOn(ClassA,“ doSomething”)時,您不是在新調用返回的對象上設置間諜,而是在ClassA函數本身上可能的doSomething函數上設置間諜。 您應該能夠執行以下操作:
it("calls method1", function() {
var originalConstructor = ClassA,
spiedObj;
spyOn(window, 'ClassA').and.callFake(function() {
spiedObj = new originalConstructor();
spyOn(spiedObj, 'method1');
return spiedObj;
});
method2();
expect(spiedObj.method1).toHaveBeenCalled();
});
請讓我知道是否行得通,否則我們可以討論更多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.