2012-11-14 4 views
0

아래에 표시된 UserMock -class라는 특정 메소드가 호출되었는지 확인해야합니다. 테스트 도중 기본 동작을 방지하기 위해 다른 모듈에 주입하는 모의 버전을 만들었습니다.이 Javascript 속성에 액세스하려면 어떻게해야합니까?

이미 sinon.js을 사용하고 있는데, isValid()과 같은 방법에 액세스하고 스파이/스텁으로 바꾸려면 어떻게해야하나요? 클래스를 인스턴스화하지 않고도이 작업을 수행 할 수 있습니까?

var UserMock = (function() { 
    var User; 
    User = function() {}; 
    User.prototype.isValid = function() {}; 
    return User; 
})(); 

prototype를 통해

답변

3
var UserMock = (function() { 
    var User; 
    User = function() {}; 
    User.prototype.isValid = function() {}; 
    return User; 
})(); 

단순히 감사합니다

(function(_old) { 
    UserMock.prototype.isValid = function() { 
     // my spy stuff 
     return _old.apply(this, arguments); // Make sure to call the old method without anyone noticing 
    } 
})(UserMock.prototype.isValid); 

설명 :

})(UserMock.prototype.isValid); 

5,

(function(_old) { 

변수 _old에있어서 isValue 참조를 만든다. 변수를 사용하여 부모 범위를 줄이지 않도록 closure가 만들어집니다.

UserMock.prototype.isValid = function() { 

프로토 타입 방법

return _old.apply(this, arguments); // Make sure to call the old method without anyone noticing 

이전 메서드를 호출하고 여기에서 결과를 반환에게 redeclares는.

apply를 사용하면 모든 인수가 함수에 전달 된 올바른 범위 (this)에 넣을 수 있습니다.
예 : 우리가 간단한 함수를 만들고 그것을 적용한다면.

function a(a, b, c) { 
    console.log(this, a, b, c); 
} 

//a.apply(scope, args[]); 
a.apply({a: 1}, [1, 2, 3]); 

a(); // {a: 1}, 1, 2, 3 
+0

결과를 잊어 버렸습니다. – xiaoyi

+0

아하 당신이 그것을 가지고 – xiaoyi

+0

내가 어떻게 작동하는지에 대한 설명을 찾을 수있는 곳을 말해 줄 수 있겠습니까? 전에이 구문을 보지 못했습니다. – Industrial

관련 문제