I am new to testing and trying to figure out how to get tested with a fairly simple controller action. The problem that I am facing does not know how to mock the methods that are inside the controller, or even think about it when appropriate.
The action creates a waiting user in the db of my webapp and returns a link to the connection. It looks like this:
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}); }); } }
The test I wrote for this method is as follows:
'use strict'; 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) {
My test is still incomplete due to the fact that I hit. As you can see from the test, I tried to make fun of the request object, as well as the first method that is called in the req.allParams() controller action. But the second method, which is potentially called in the controller, is res.badRequest() , which is a function built into the res object in the sails.js file ,
This function does not know how to prototype. Moreover, thinking about bullying this function raises all sorts of other questions. Why am I mocking this feature at all? The logic of unit testing, I think, is that you test parts of your code in isolation with others, but is it not that far? It also generates a lot of extra work, because I will need to model the behavior of this function, which may or may not be simple to achieve.
The code I wrote here is based on several instructions of the type conceptual type (see here , here and here ), but these messages do not address the problem in which you have methods on req and / or res objects in the controller.
How to approach the solution? Any insight would be greatly appreciated!