spyon不能在非angularjs环境中使用嵌套函数

时间:2016-06-29 16:58:58

标签: javascript karma-jasmine spyon

我有一个问题是在我的javascript模块中调用从另一个函数调用的函数(没有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控制器中进行相同的测试,它将使用$ scope而不是myApp

有任何帮助吗?

1 个答案:

答案 0 :(得分:0)

getFunction2中引用的getFunction1是范围函数getFunction2,而不是myApp的getFunction2实例。间谍正在监视实例的getFunction2

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

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

    return value1 + value2;
};