1

Trying to unit test my small api, I need to test the save errors and successes (already signed up, etc).

Currently here is my code: models/auth.js

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

var AuthSchema = Schema({
    id: String,
    user: String,
    password: String,
    origin: String,
});

//Export model
module.exports = mongoose.model('user', AuthSchema);

tests/api.test.js

const chai = require('chai');
const should  = chai.should;
const expect = chai.expect;
const assert = chai.assert;
/ Node Http Mocks
var httpMocks = require('node-mocks-http');

var util = require('util'),
    express = require('express'),
    bodyParser = require('body-parser'),
    validator = require('express-validator'),
    app = express();

var authController = require('../controllers/auth');

describe("Test AUTH Calls ", function() {
    var mongoHost = 'mongodb://localhost:27017/testingDB';

    // model
    var authModel = require('../models/auth.js');

    var Mongoose = require('mongoose').Mongoose;
    var mongoose = new Mongoose();

    var Mockgoose = require('mockgoose').Mockgoose;
    var mockgoose = new Mockgoose(mongoose);

    // Generate a v1 UUID (time-based)
    const uuidV1 = require('uuid/v1');

    before(function(done) {
        mockgoose.prepareStorage().then(function() {
            mongoose.Promise = global.Promise;
            mongoose.connect(mongoHost, {
                keepAlive: true,
                reconnectTries: Number.MAX_VALUE,
                useMongoClient: true
            },function(err) {
                done(err);
            });
            mongoose.connection.on('connected', function(err) {
                if (err) {
                    console.log('Error on DB Connection: ', err);
                } else {
                    console.log('Db Connection opened!');
                }

            });
        });
    });

it("should warn that the user already exists", function(done) {
        var req = httpMocks.createRequest({
            method: 'GET',
            url: '/signup',
            body: {
                'username': 'tricky',
                'password': 'frasier'
            }
        });
        var res = httpMocks.createResponse();


        var userModel = new authModel({
            id: uuidV1(),
            username: req.body.username,
            password: req.body.password
        });

        userModel.save(function(err) {
            if (err) {
                console.log('Error while registering a user.', err.name);
            } else {
                console.log('User saved successfully.');
            }
        });

        var userN = req.body.username;

        // Check if already exists
        var myUser = null;
        authModel.findOne({
            username: userN,
        }, function(err, user) {
            if (err) {
                console.log('Error while verifying a user.', err.name);
            }
            if (user) {
                console.log('User exists.');
                myUser = user;
            }

        });

        authController.signup(req, res); // Will fail on user existing
        assert.equal(res.statusCode, 401);
        done();
    });

});

Now the issue is that the first console.log says 'DB Connection opened!', and if I do a console log of the model (userModel) after filled in, it logs correctly, but my issue is on save. I don't know if it saves or not but no console log from inside shows, failure or success.

Can anyone tell me what I am doing wrong ?

Thank you

Ederico Rocha
  • 250
  • 4
  • 10

3 Answers3

1

To me it worked by changing this:

var Mongoose = require('mongoose').Mongoose;
var mongoose = new Mongoose();

var Mockgoose = require('mockgoose').Mockgoose;
var mockgoose = new Mockgoose(mongoose);

with

var mongoose = require('mongoose');
var { Mockgoose } = require('mockgoose');

var mockgoose = new Mockgoose(mongoose);
pinturic
  • 2,253
  • 1
  • 17
  • 34
  • I know this post is old, but do you have any idea why it works this way and not the way it is specified in the Mockgoose documentation? Btw, thanks this solved my issues too :) – Luki Nov 01 '18 at 11:19
  • 1
    I think the API have changed. Now mockgoose should have updated docs – pinturic Nov 02 '18 at 16:25
0

you should instantiate Schema using new keyword like this L

var AuthSchema = new Schema({
    id: String,
    user: String,
    password: String,
    origin: String,
});
El houcine bougarfaoui
  • 35,805
  • 9
  • 37
  • 37
0

The code is async, so probably done() is being called before the console.log commands. You should put one callback inside another or convert the code to use Promise.

Jon Ribeiro
  • 21
  • 1
  • 5