5

我正在使用 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 调用。

谢谢你的帮助。

4

1 回答 1

0

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

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的存根函数进行模拟,如上所述。

于 2014-09-05T15:43:59.167 回答