node.js - 使用 Mocha 测试 Express 和 Mongoose

标签 node.js testing express mongoose mocha.js

我正在尝试使用 Mocha 和 Chai 测试我的 REST API 端点处理程序,该应用程序是使用 Express 和 Mongoose 构建的。我的处理程序主要采用以下形式:

var handler = function (req, res, next) {
    // Process the request, prepare the variables

    // Call a Mongoose function
    Model.operation({'search': 'items'}, function(err, results) {
        // Process the results, send call next(err) if necessary

        // Return the object or objects
        return res.send(results)
    }
}

例如:

auth.getUser = function (req, res, next) {
    // Find the requested user
    User.findById(req.params.id, function (err, user) {
        // If there is an error, cascade down
        if (err) {
            return next(err);
        }
        // If the user was not found, return 404
        else if (!user) {
            return res.status(404).send('The user could not be found');
        }
        // If the user was found
        else {
            // Remove the password
            user = user.toObject();
            delete user.password;

            // If the user is not the authenticated user, remove the email
            if (!(req.isAuthenticated() && (req.user.username === user.username))) {
                delete user.email;
            }

            // Return the user
            return res.send(user);
        }
    });
};

这个问题是函数在调用 Mongoose 方法和测试用例时返回,如下所示:

it('Should create a user', function () {
    auth.createUser(request, response);

    var data = JSON.parse(response._getData());
    data.username.should.equal('some_user');
});

在做任何事情之前,永远不要通过函数返回。使用 Mockgoose 模拟 Mongoose,使用 Express-Mocks-HTTP 模拟请求和响应对象。

虽然使用 superagent 和其他请求库相当普遍,但我更愿意单独测试功能,而不是测试整个框架。

有没有办法让测试在评估 should 语句之前等待,而不更改我正在测试的返回 promise 的代码?

最佳答案

您应该使用测试的异步版本,方法是为 it 提供一个带有 done 参数的函数。

有关详细信息,请参阅 http://mochajs.org/#asynchronous-code .

由于您不想修改代码,一种方法是在测试中使用 setTimeout 等待调用完成。

我会尝试这样的事情:

it('Should create a user', function (done) {
    auth.createUser(request, response);

    setTimeout(function(){
        var data = JSON.parse(response._getData());
        data.username.should.equal('some_user');

        done(); 
     }, 1000); // waiting one second to perform the test
});

(可能有更好的方法)

关于node.js - 使用 Mocha 测试 Express 和 Mongoose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28962464/

相关文章:

node.js - 检测管道流操作的结束

Hadoop 迷你集群模拟 (MiniDFSCluster)

testing - 用于测试的备用 Perl 环境

javascript - 如何在node.js(Express)中使用通过res.render传递的字典

node.js - 在 Express 中更改 cookie 过期时间

node.js - Express 路由器创建不需要的新 session

node.js - 管理文件上传到 Nodejs 的安全性

javascript - 亚马逊 Alexa - 捕获完整的成绩单

javascript - Redis Store 没有 get 方法?

r - 对表中的多个变量应用 t 检验和 Wilcoxon 检验