2

我想 通过在我的测试中使用proxyquire来模拟 MongoDB 依赖项:

var proxyquire = require('proxyquire');
var controller = path.resolve('.path/to/controller/file.js');

每个语句之前:

mocked_mongoose = {
     isMocked: true,
     model: function(name, schema, collection, skipInit) {
         return {
             find: function(conditions, projection, options, callback) {
                 console.log('callback find');
                 return callback();
             },
             save: function(options, fn) {
                 console.log('callback save');
                 return callback();
             },
             findOne: function(conditions, projection, options, callback) {
                 console.log('callback find one');
                 var model = mongoose.model(name);
                 var fakeModel = fakery.fake(model);
                 return callback(null, fakemodel);
             }
         }
     }
 };

proxyquire(controller, {
     'mongoose': mocked_mongoose
 });

当我去控制器并执行 console.log(mongoose.isMocked) 时,我得到了 undefined 并且如果我打印 mongoose.model.toString() 似乎 mongoose 方法没有被覆盖。

我跟进了这篇文章并尝试实现相同的逻辑,但我没有得到相同的结果。

任何帮助将不胜感激,谢谢!

4

1 回答 1

1

最后我改变了定义我的模拟猫鼬对象的方式,以完全匹配我想在 mt 案例中测试的场景:

第一个模型实例化

var Model = mongoose.model('SchemaDef');
var other = Model({
 _id:'someId'
 name'Some other fields'
});

型号搜索:

Model.findOne(query, callback);

这个版本是如何工作的:

'use strict';
var factory = require('factory-girl');
var mongoose = require('mongoose');

    function viewModel(name){
        function constructor(obj){
            if(obj){
                obj.find = constructor.find;
                obj.save = constructor.save;
                obj.findOne = constructor.findOne;
            }
            return obj;

        };
        constructor.isMocked = true;
        constructor.find = function(query, callback){
            factory.build(name, function(err, mockedModel){
                return callback(null,[mockedModel]);
            });

        };

        constructor.save = function(callback){
            factory.build(name, function(err, mockedModel){
                return callback(null,[mockedModel]);
            });
        };

        constructor.findOne=function(query,callback){
            factory.build(name, function(err, mockedModel){
                return callback(null,mockedModel);
            });
        };

        return constructor;
    };

module.exports = {
    model:function(name){
        factory.define(name, mongoose.model(name));
        return viewModel(name);
    }
};
于 2016-01-21T15:21:48.830 回答