【问题标题】:How do you mock MySQL (with node-orm2) in Node.js/Express?你如何在 Node.js/Express 中模拟 MySQL(使用 node-orm2)?
【发布时间】:2014-09-05 23:43:59
【问题描述】:

我正在使用 node.js/express 和 https://github.com/dresende/node-orm2 来使用我的 MySQL 数据库。

我是 node.js 世界的新手,到目前为止我很困惑,我不知道如何对一个简单的函数进行单元测试(不是集成测试)。

这是我的 server.js,正在加载我的用户模型 (ORM)

var express = require('express'),
    orm = require('orm'),
    config = require('./config/config.js'),
    auth = require('./services/authentication'),
    helper = require('./middlewares/helper.js'), 
    friends = require('./modules/friends.js');

var app = express();

app.use(orm.express('mysql://' + config.mysql.username + ':' + config.mysql.pwd + '@' + config.mysql.host + ':' + config.mysql.port + '/' + config.mysql.db, {
    define: function(db, models, next) {
        db.load("./models/models.js", function(err) { // loaded!
            models.user = db.models.user;
        });
    }
}));

var middlewares = [auth.authenticate, helper.retrieveUser];

app.get('/friends', middlewares, friends.findActiveFriends);

app.listen(3000);
console.log('Listening on port 3000...');

这是用户模型:

module.exports = function (db, cb) {
    var User = db.define('user', {
        uid               : { type: 'number', rational: false, unique: true, required: true },
        first_name        : { type: 'text', size: 100, required: true },
        last_name         : { type: 'text', size: 100, required: true },
        picture           : { type: 'text', size: 255, required: false },
        email             : { type: 'text', size: 255, required: true }, 
        creation_date     : { type: 'date', time: true },
        modification_date : { type: 'date', time: true }
    }, {
        methods: {
            fullName: function () {
                return this.first_name + ' ' + this.last_name;
            }
        },
        hooks: {
            beforeCreate: function (next) { 
                if (this.creation_date == undefined) {
                    this.creation_date = new Date();
                }
                if (this.modification_date == undefined) {
                    this.modification_date = new Date();
                }
                return next();
            } 
        }
    });

    // CUSTOM FUNCTIONS
    User.getByUid = function(uid, callback) {
        this.find({ uid: uid }, function(err, users) {
            if(err) callback(err);
            if (users.length == 1) { 
                callback(null, users[0]); 
            } else {
               callback('No user found with uid=' + uid);
            }
        });
    }; 

    User.hasMany("friends", User, {
        status: { type: 'enum', values: ['pending', 'refused', 'active'] }
    }, {
        reverse: 'friendsrev', mergeId: 'user_id', mergeAssocId: 'friend_id'
    });

    return cb();
};

这是我在friends.js中找到活跃朋友的方法:

var _findActiveFriends = function(req, res) {
    req.currentUser.getFriends({
        status: 'active'
    }, function(err, friends) {
        if (err) throw err;
        res.send(JSON.stringify(friends));
    });
};

我想知道如何通过模拟数据库连接和请求来编写一个简单的测试(使用 mocha 和 sinon.js?)。我需要模拟 req.currentUser 的值,它是 ORM 在中间件中返回的用户。

我只想运行单元测试,不使用真实数据库或进行一些 HTTP 调用。

感谢您的帮助。

【问题讨论】:

    标签: mysql node.js unit-testing express mocking


    【解决方案1】:

    如果您想使用 sinon.js 模拟 req,您可以执行以下操作。

    var sinon = require('sinon');
    var friend = require('./friend');
    
    it('some test', function(done) {
      var req = {
        currentUser: {
          // Add all the properties/functions that you are concerned with here. 
          // and you can/should wrap them around sinon.spy().
          // If you are not concerned with that function (i.e. you are not using it) 
          // then you can simply use sinon.stub() to return a stub function. 
        }
      };
      var res = {
        send: sinon.spy(function(obj) { 
          assert.ok(obj); // yes object exists 
          done(); // end of test
        };
      };
      var next = function() {};
      friend.findActiveFriend(req, res, next);
    });
    

    这样你不应该连接到模型,它只测试friend.js

    另外,由于我刚刚注意到您正在使用orm.express,您可能还想简单地模拟req.models,并使用您想要的上述存根函数。

    【讨论】:

      猜你喜欢
      • 2012-01-13
      • 1970-01-01
      • 1970-01-01
      • 2014-06-29
      • 1970-01-01
      • 2011-06-30
      • 2022-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多