samedi 20 décembre 2014

Mocha setup mongoose models

I want to start my server and then test the endpoints. My server.js loades all models and routes, but when it gets to the before each function, I get the following error.



Uncaught MissingSchemaError: Schema hasn't been registered for model "Test".
Use mongoose.model(name, schema)


I understand that I could register the models in the testfile as suggested in the error message but is that really needed?


controllerTest.js



(function () {
"use strict";

var app = require("../../../server");
var should = require("should"),
mongoose = require("mongoose"),
mockgoose = require("mockgoose");

var request = require("supertest"),
agent = request.agent(app);

mockgoose(mongoose);


var test;

describe("Test Controller", function () {

beforeEach(function (done) {
var Test = mongoose.model("Test");
test = new Test({});
test.save(function (error, savedObj) {});
done();
});
})
}());


server.js



(function () {
'use strict';

console.log("Starting Server...");
var express = require('express'),
config = require('./config/defaultConfig'),
mongoose = require('mongoose');

mongoose.connect('host', 'datastore');

var port = config.server.port || 9000;
var app = express();
app.config = config;
require('./config/expressConfig')(app, express);
require('./config/modelsConfig').getModels(requireResource);
require('./config/routesConfig').getRoutes(requireResource);

function requireResource(files, isAppRequired) {

files.forEach(function (file) {
(isAppRequired) ? require(file)(app) : require(file)();
});
}

app.listen(port);
console.log("Server started at port: " + port);

exports = module.exports = app;
}());


modelsConfig.js



(function () {
"use strict";

var glob = require("glob"),
config = require("./defaultConfig");

module.exports.getModels = function (callback) {
glob("/**/**/*Model.js", {
root: config.server.rootPath + "/server"
}, function (error, matches) {
callback(matches, false);
});
}
}());


I console logged the matches and require calls and it seems that they get called before the testfile reaches before each.


Aucun commentaire:

Enregistrer un commentaire