【问题标题】:How to test method in controller in sails.js using Mocha + Sinon?如何使用 Mocha + Sinon 在sails.js 中的控制器中测试方法?
【发布时间】: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

这个函数我不知道怎么模拟。此外,考虑模拟这个功能会引发各种其他问题。为什么我首先要模拟这个功能?我认为,单元测试的逻辑是,您将部分代码与其他代码隔离开来,但这不是有点过分吗?它还会产生大量额外的工作,因为我需要模拟这个函数的行为,这可能会也可能不会很容易完成。

我在这里编写的代码基于几个概念验证类型的教程(请参阅 hereherehere),但这些帖子并未涉及以下问题:您在控制器中的 req 和/或 res 对象上有方法。

在这里解决解决方案的正确方法是什么?任何见解将不胜感激!

【问题讨论】:

    标签: unit-testing sails.js mocha.js sinon


    【解决方案1】:

    您正在尝试在待处理的用户控制器上测试创建操作并断言它的响应/行为。你可以做的实际上是向Supertest发出请求来测试它。

    我假设你已经 bootstrapped your test 使用 Mocha 和 should.js。

     var request = require('supertest');
    
     describe('PendingUsersController', function() {
    
      describe('#create()', function() {
         it('should create a pending user', function (done) {
           request(sails.hooks.http.app)
             .post('/pendinguser') 
             //User Data
             .send({ name: 'test', emailAdress: 'test@test.mail', affiliation: 'University of JavaScript', title: 'Software Engineer' })
             .expect(200)
             .end(function (err, res) {
                  //true if response contains { message : "Your are pending user."}
                  res.body.message.should.be.eql("Your are pending user.");
             });
          });
        });
     });
    

    更多关于控制器测试Sails.js from docs 或查看this example 项目了解更多信息。

    【讨论】:

      猜你喜欢
      • 2021-01-01
      • 1970-01-01
      • 2018-05-05
      • 1970-01-01
      • 1970-01-01
      • 2019-03-24
      • 1970-01-01
      • 2017-10-08
      • 1970-01-01
      相关资源
      最近更新 更多