mercredi 6 juillet 2016

How to do unit test in dependent modules (node.js)?

I have an application with two modules (Book and User). The book model looks like this:

var mongoose = require('mongoose'),
Schema = mongoose.Schema;

var BookModel = new Schema({

    name: String,
    author: String,
    description: String,
    _user: {type: Schema.Types.ObjectId, ref: 'User'}

});

module.exports = mongoose.model('Book', bookModel);

And the user model:

var mongoose = require('mongoose'),
    bcrypt = require('bcryptjs'),
    Schema = mongoose.Schema;

var userModel = new Schema({

  name: String,
  username: String,
  password: String,

});

module.exports = mongoose.model('User', userModel);

I want to do a unit test in the POST method (inserting a book in the DB) with the condition of not allowing empty name. This is what I have in the POST method:

var post = function (req, res) {
    var bookNew = new book(req.body);

    // get paylod from the user's token
    var payload = tokenManager.getPayload(req.headers);

    if (req.body._user)
        delete req.body._user;

    if (!req.body.name) {
        res.status(400);
        res.send("Name is required");
    } else if (payload == null || payload == undefined) {
        res.status(400);
        res.send("Token error");
    } else {
        // store the user id
        bookNew.set('_user', payload.id);

        bookNew.save();
        res.status(201);
        res.send("Book saved");
    }
};

As you can see, I get the payload from the token (created when the user is logged in). I do this because the payload contains the user id and, then, I insert it in _user (property in book model).

The problem is that if I do a unit test in order to verify if the book’s property (name) is filled, I don’t have a user to retrieve the payload. Therefore, the payload will be undefined and the book unit test will not be successful in any case. Do you have any suggestion on what I should do? It looks like I have to create a user in order to test all book modules… but I am not sure if that is the most suitable solution.

Aucun commentaire:

Enregistrer un commentaire