1

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 }.

テストでユーザーを設定したので、戻り値はユーザーの配列になるはずです。(現在の状態ではまだテストに失敗しますが、2 番目の return ステートメントのコメントを外すと、理論的にはパスするはずです。) 代わりに、users 配列は空として表示されます。

テスト モデルから値を取得してカスタム関数に表示するにはどうすればよいですか?

4

1 に答える 1