2016-06-29 37 views
0

我有一个问题spyon一个从另一个函数在我的JavaScript模块调用的函数(无angularJS)spyon不会在非angularjs环境嵌套函数工作

这是JavaScript模块:

var Utils = function() { 

function getFunction1(value1) { 
    var value2 = getFunction2(); 

    return value1 + value2; 
}; 

function getFunction2() { 

    return 10; 
}; 

return { 
    getFunction1: getFunction1, 
    getFunction2: getFunction2 
}; 
}; 

我的测试是:

describe('test spyon', function() { 

var myApp = new Utils(); 
it('test spyOn', function() { 

    spyOn(myApp, 'getFunction2').and.returnValue(2); 

    // call a function under test and assert 
    expect(myApp.getFunction1(1)).toBe(3); 
}); 
}); 

我运行命令:

gradle build karma 

,其结果是:

PhantomJS 1.9.8 (Windows 7 0.0.0) test spyon test spyOn FAILED 
Expected 11 to be 3. 
Error: Expected 11 to be 3. 
    at X:/projects/ETRANS-CALCULATOR/branches/ONS128-ONS129-LifeIPCalculators/Common/src/test/webapp/unit/utilsSpec.js:30 
    at X:/projects/ETRANS-CALCULATOR/branches/ONS128-ONS129-LifeIPCalculators/Common/node_modules/karma-jasmine/lib/boot.js:126 
    at X:/projects/ETRANS-CALCULATOR/branches/ONS128-ONS129-LifeIPCalculators/Common/node_modules/karma-jasmine/lib/adapter.js:171 
    at http://localhost:9876/karma.js:182 
    at http://localhost:9876/context.html:67 
PhantomJS 1.9.8 (Windows 7 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.946 secs/0.002 secs) 
:Common:karma FAILED 

如果我做同样的测试在AngularJS控制器,将工作使用$范围,而不是对myApp

任何帮助吗?

回答

0

getFunction1中引用的getFunction2是范围函数getFunction2,而不是myApp的getFunction2的实例。尽管如此,间谍正在侦察实例的getFunction2

要解决此问题,您应该在getFunction1而不是getFunction2中使用this.getFunction2

function getFunction1(value1) { 
    var value2 = this.getFunction2(); 

    return value1 + value2; 
}; 
+0

酷,这个工作,而不是一个协议,我必须要改变这种添加,如果我想用茉莉花和spyOn嘲笑他们的所有调用嵌套函数。有更好的方法来做到这一点?为什么我使用$ scope它的作用? – carlitos081

+0

你可以显示代码在哪里使用$范围,它的工作原理? –

+0

我刚刚发布了AngularJS,我总是使用“$ scope”来完成“this”的操作:$ scope.function1调用$ scope.function2 – carlitos081