2016-06-29 12 views
0

내가 내 자바 스크립트 모듈에서 다른 함수에서 호출되는 함수 (NO AngularJS와)spyon는

이 자바 스크립트 모듈을 spyon하는 문제가있어 비 AngularJS와 환경에서 중첩 된 기능을 작동하지 않습니다

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); 
}); 
}); 

내가 명령을 실행 (210)

그리고 그 결과는 다음과 내가 AngularJS와 컨트롤러에서 동일한 테스트를 할 경우

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 

가 대신

어떤 도움을 myApp

의 $ 범위를 사용하여 작동합니다?

답변

0

getFunction1에서 참조 된 getFunction2은 범위 적용 getFunction2이며 myApp의 인스턴스는 getFunction2이 아닙니다. 스파이가 인스턴스의 getFunction2을 감시하고 있습니다.

이 문제를 해결하려면 getFunction2이 아닌 getFunction1this.getFunction2을 사용해야합니다. 쿨 즉

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

    return value1 + value2; 
}; 
+0

,이, 내가 재스민과 spyOn 그들을 조롱하고자 할 경우에 추가 중첩 된 함수에 대한 모든 호출을 변경할 필요가 없습니다 거래를했다. 더 좋은 방법이 있습니까? 왜 $ scope를 사용합니까? – carlitos081

+0

$ scope를 사용하는 코드를 보여줄 수 있습니까? –

+0

방금 ​​AngularJS에서 "this"와 정확히 일치하는 "$ scope"를 사용했습니다. $ scope.function1 call $ scope.function2 – carlitos081