NodeJS mockgoose保存模型似乎不起作用

时间:2017-11-05 17:07:45

标签: node.js unit-testing mongoose chai mockgoose

尝试对我的小api进行单元测试,我需要测试保存错误和成功(已经注册等)。

目前这是我的代码: 的模型/ 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);

测试/ 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();
    });

});

现在的问题是,第一个console.log表示“数据库连接已打开!”,如果我在填写后执行模型的控制台日志(userModel),它会正确记录,但是我的问题是保存。我不知道它是否保存,但是没有来自内部的控制台日志显示,失败或成功。

谁能告诉我我做错了什么?

谢谢

3 个答案:

答案 0 :(得分:1)

对我来说,通过改变它来起作用:

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

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

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

var mockgoose = new Mockgoose(mongoose);

答案 1 :(得分:0)

您应该使用{L

这样的Schema关键字来实例化new
var AuthSchema = new Schema({
    id: String,
    user: String,
    password: String,
    origin: String,
});

答案 2 :(得分:0)

代码是异步的,所以可能在console.log命令之前调用done()。你应该把一个回调放在另一个回调或转换代码以使用Promise。