2013-08-23 5 views
2

몽구스 모델의 가상 속성을 스텁하는 방법이 있습니까?몽구스 모델의 스터 빙 가상 속성

Problem은 모델 클래스이고 difficulty은 가상 속성이라고 가정합니다. delete Problem.prototype.difficulty은 false를 반환하고 속성은 그대로 있으므로 원하는 값으로 대체 할 수 없습니다.

는 또한
var p = new Problem(); 
delete p.difficulty; 
p.difficulty = Problem.INT_EASY; 

그것은 작동하지 않았다

을 시도했다. 문자열 속성의 어려움을 래핑하는 시도 : 오류 "형식 오류를 슬로우

var p = new Problem(); 
    sinon.stub(p, 'difficulty').returns(Problem.INT_EASY); 

을하는 동안,"재산 '의 범위를'정의의 읽을 수 없습니다 형식 오류 "Problem.prototype.difficulty에 정의되지 않은 할당하거나 예외를 던질 것 sinon.stub(Problem.prototype, 'difficulty').returns(Problem.INT_EASY); 를 사용

기능으로 ".

아이디어가 부족합니다. 도와주세요! 감사!

답변

2

몽구스 internally usesObject.defineProperty 모든 속성. 구성 할 수없는 것으로 정의되었으므로 delete 수 없으며 그 중 하나도 re-configure 수 없습니다.

는하지만, 얻을 모든 속성 설정하는 데 사용되는 모델의 getset 방법, 덮어 쓰기됩니다 할 수있는 일 :

var p = new Problem(); 
p.get = function (path, type) { 
    if (path === 'difficulty') { 
    return Problem.INT_EASY; 
    } 
    return Problem.prototype.get.apply(this, arguments); 
}; 

을 또는을 완전한 예를 사용 sinon.js :

var mongoose = require('mongoose'); 
var sinon = require('sinon'); 

var problemSchema = new mongoose.Schema({}); 
problemSchema.virtual('difficulty').get(function() { 
    return Problem.INT_HARD; 
}); 

var Problem = mongoose.model('Problem', problemSchema); 
Problem.INT_EASY = 1; 
Problem.INT_HARD = 2; 

var p = new Problem(); 
console.log(p.difficulty); 
sinon.stub(p, 'get').withArgs('difficulty').returns(Problem.INT_EASY); 
console.log(p.difficulty); 
+0

재정의'하나를 포함, 조언,하지만 sinon와 스텁 것은 형식 오류가 발생합니다 : 정의되지 않은 재산 '생성자'을 읽을 수 없습니다. 그래서 첫 번째 해결책을 사용했습니다. 감사! –

+0

나는 나를 위해 일하는 sinon으로 완전한 예제를 올렸다. ([email protected], [email protected], [email protected]). –

+0

예제의 problemSchema에'regionId'를 추가했습니다. 이제 sinon으로 스터 빙 한 후에 regionId를 할당 할 수 없습니다. 그래서 내가'[ 'Silversword', 'Ainsley Field']를 주장하려고 할 때 오류가 발생했습니다. should.include (p.regionId); ' –

0

2017 년 말 현재 Sinon 버전에서 일부 인수 (예 : 몽구스 모델의 가상 만)를 다음과 같은 방식으로 스터 빙할 수 있습니다.

const ingr = new Model.ingredientModel({ 
    productId: new ObjectID(), 
    }); 

    // memorizing the original function + binding to the context 
    const getOrigin = ingr.get.bind(ingr); 

    const getStub = S.stub(ingr, 'get').callsFake(key => { 

    // stubbing ingr.$product virtual 
    if (key === '$product') { 
     return { nutrition: productNutrition }; 
    } 

    // stubbing ingr.qty 
    else if (key === 'qty') { 
     return { numericAmount: 0.5 }; 
    } 

    // otherwise return the original 
    else { 
     return getOrigin(key); 
    } 

    }); 

이 솔루션은 다른의 무리에 의해 영감을 작품 get` @Adrian 하이네