0

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 コントローラーで同じテストを行うと、myApp の代わりに $scope を使用して動作します

何か助けはありますか?

4

1 に答える 1

0

getFunction2参照されてgetFunction1いるのはスコープ付きの関数getFunction2であり、myApp の のインスタンスではありませんgetFunction2。スパイはインスタンスをスパイしていますgetFunction2

これを修正するには、ではなくthis.getFunction2inを使用する必要があります。getFunction1getFunction2

すなわち

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

    return value1 + value2;
};
于 2016-06-29T20:16:33.883 に答える