【发布时间】:2015-04-19 14:41:50
【问题描述】:
我是测试新手,并试图了解如何测试一个相当简单的控制器操作。我遇到的问题是不知道如何模拟控制器内部的方法,甚至不知道什么时候这样做是合适的。
该操作在我的 webapp 的数据库中创建一个待处理用户并返回一个加入链接。它看起来像这样:
module.exports = {
create: function(req, res, next) {
var name,
invitee = req.allParams();
if ( _.isEmpty(invitee) || invitee.name === undefined) {
return res.badRequest('Invalid parameters provided when trying to create a new pending user.');
}
// Parse the name into its parts.
name = invitee.name.split(' ');
delete invitee.name;
invitee.firstName = name[0];
invitee.lastName = name[1];
// Create the pending user and send response.
PendingUser.create(invitee, function(err, pending) {
var link;
if (err && err.code === 'E_VALIDATION') {
req.session.flash = { 'err': err };
return res.status(400).send({'err':err});
}
// Generate token & link
link = 'http://' + req.headers.host + '/join/' + pending.id;
// Respond with link.
res.json({'joinLink': link});
});
}
}
我为此方法编写的测试如下所示:
'use strict';
/**
* Tests for PendingUserController
*/
var PendingUserController = require('../../api/controllers/PendingUserController.js'),
sinon = require('sinon'),
assert = require('assert');
describe('Pending User Tests', function(done) {
describe('Call the create action with empty user data', function() {
it('should return 400', function(done) {
// Mock the req object.
var xhr = sinon.useFakeXMLHttpRequest();
xhr.allParams = function() {
return this.params;
};
xhr.badRequest
xhr.params = generatePendingUser(false, false, false, false);
var cb = sinon.spy();
PendingUserController.create(xhr, {
'cb': cb
});
assert.ok(cb.called);
});
});
}
function generatePendingUser(hasName, hasEmail, hasAffiliation, hasTitle) {
var pendingUser = {};
if (hasName) pendingUser.name = 'Bobbie Brown';
if (hasEmail) pendingUser.emailAddress = 'bobbie.brown@example.edu';
if (hasAffiliation) pendingUser.affiliation = 'Very Exclusive University';
if (hasTitle) pendingUser.title = "Assistant Professor";
return pendingUser;
}
由于遇到了障碍,我的测试仍未完成。正如您从测试中看到的那样,我尝试模拟请求对象以及在控制器操作req.allParams() 中调用的第一个方法。但是控制器中可能调用的第二种方法是res.badRequest(),也就是function built into the res object within sails.js。
这个函数我不知道怎么模拟。此外,考虑模拟这个功能会引发各种其他问题。为什么我首先要模拟这个功能?我认为,单元测试的逻辑是,您将部分代码与其他代码隔离开来,但这不是有点过分吗?它还会产生大量额外的工作,因为我需要模拟这个函数的行为,这可能会也可能不会很容易完成。
我在这里编写的代码基于几个概念验证类型的教程(请参阅 here、here 和 here),但这些帖子并未涉及以下问题:您在控制器中的 req 和/或 res 对象上有方法。
在这里解决解决方案的正确方法是什么?任何见解将不胜感激!
【问题讨论】:
标签: unit-testing sails.js mocha.js sinon