2014-02-17 1 views
1

Mongoose 모델에서 사용자 정의 메소드를 테스트하려고하지만 테스트 모델에서 설정 한 값이 사라지고 테스트가 실패하게됩니다. 시험은 다음과 같습니다Jasmine-Node로 테스트 할 때 Mongoose 모델 사용자 정의 함수에서 사라지는 값

it('should get the friend id', function(){ 
    var conversation = new Conversation({ 
     'users': [new ObjectId('0'), new ObjectId('1')] 
    }); 

    expect(conversation.getFriendId('0')).toEqual(new ObjectId('1')); 
}); 

내 모델 선언이 포함되어 있습니다

var mongoose = require('mongoose'); 
var ObjectId = mongoose.Schema.Types.ObjectId; 

var ConversationSchema = new mongoose.Schema({ 
    'users': [{'type': ObjectId, 'ref': 'User'}] 
}); 

ConversationSchema.methods.getFriendId = function(userId) { 
    return this.users; 
    //return this.users[0] === new ObjectId(userId) 
    // ? this.users[1] : this.users[0]; 
}; 

module.exports = mongoose.model('Conversation', ConversationSchema); 

내가 테스트를 실행하면, 내가 얻을 :

Expected [ ] to equal { path : '1', instance : 'ObjectID', validators : [ ], setters : [ ], getters : [ ], options : undefined, _index : null }. 

내가 테스트에서 사용자를 설정, 따라서 반환 값은 사용자 배열이어야합니다. (테스트는 여전히 현재 상태에서 실패하지만 두 번째 return 문에서 주석을 제거 할 때 이론적으로 통과해야합니다.) 대신 사용자 배열이 비어있는 것으로 표시됩니다.

테스트 모델의 값을 내 사용자 지정 함수에 표시하려면 어떻게합니까?

답변

1

마침내 작동하게하려면 여러 가지가 변경되었습니다.

사용자 배열을 set-like object으로 바꿨습니다. 데이터를보다 정확하게 나타 내기 때문입니다. 집합의 키는 ObjectId의 문자열입니다.

새 ObjectId를 만들려면 12 바이트 문자열 또는 24 문자 16 진 문자열이 있어야합니다. 원래는 한자리 숫자 문자열로 처리하려고했습니다. 24 자 16 진수 문자열로 더미 ID를 저장하는 spec 도우미를 추가했습니다.

mongoose.Schema.Types.ObjectIdmongoose.Types.ObjectId은 서로 다른 두 가지입니다. 나는 둘 다 사용할 필요가 있음을 깨닫기 전에 각 것을 시도했다. 스키마를 만들 때 mongoose.Schema.Types.ObjectId이 필요합니다. Any other time I'm referring to the type ObjectId, I need mongoose.Types.ObjectId.

모델에 액세스하기 위해 파일을 정의한 파일에서 모델을 반환하려고했습니다. 대신 내 모델을 얻으려면 mongoose.model()으로 전화해야했습니다. 이러한 변화와

내 모델 정의는 이제 다음과 같습니다

내 테스트는 다음과 같습니다
var mongoose = require('mongoose'); 
var ObjectId = mongoose.Schema.Types.ObjectId; 

var ConversationSchema = new mongoose.Schema({ 
    'users': Object, 
    'messages': [ 
     { 
      'text': String, 
      'sender': {'type': ObjectId, 'ref': 'User'} 
     } 
    ] 
}); 

ConversationSchema.methods.getFriendId = function(userId) { 
    for (var u in this.users) { 
     if (u !== userId) return new mongoose.Types.ObjectId(u); 
    } 

    return null; 
}; 

// other custom methods... 

mongoose.model('Conversation', ConversationSchema); 

:

describe('getFriendId()', function(){ 
    var mongoose = require('mongoose'); 
    var ObjectId = mongoose.Types.ObjectId; 

    require('../../../models/Conversation'); 
    var Conversation = mongoose.model('Conversation'); 

    var helper = require('../spec-helper'); 

    it('should get the friend id', function(){ 
     users = {}; 
     users[helper.ids.user0] = true; 
     users[helper.ids.user1] = true; 

     var conversation = new Conversation({ 'users': users }); 

     expect(conversation.getFriendId(helper.ids.user0)).toEqual(new ObjectId(helper.ids.user1)); 
    }); 
});