I have a folder structure of:
- app
- config
- config.js // environment variables
- express.js // creates an express server
- passwords
- passwords.controller.js
- passwords.route.js
- passwords.test.js
- index.js // main app file
My index file loads the app asynchronously:
function initMongoose() {
...
return mongoose.connect(config.mongo.host, {useNewUrlParser: true, keepAlive: 1})
.then((connection) => {
// Password is a function which connects the Password schema to the given connection
Password(connection);
})
.catch((e) => {
throw new Error(`Unable to connect to database: ${config.mongo.host}`);
});
}
async init() {
await initMongoose();
const app = require('./config/express');
const routes = require('./index.route');
app.use('/api', routes);
...
app.listen(3000, () => {
console.log('server started');
});
}
module.exports = init();
My test files are constructed like this:
// Load the app async first then continue with the tests
require('../index').then((app) => {
after((done) => {
mongoose.models = {};
mongoose.modelSchemas = {};
mongoose.connection.close();
done();
});
describe('## Passwords API', () => {
...
});
});
I'm starting the tests like this:
"test": "cross-env NODE_ENV=test ./node_modules/.bin/mocha --ui bdd --reporter spec --colors server --recursive --full-trace"
Here's where the weirdness gets the better of me. Basically it loads passwords.controller.js
before anything else, this is because of the --recursive
option. This should not happen since index.js
needs to load first so it can connect to mongoose etc before any of the tests runs, if it doesn't then this snippet from passwords.controller.js
will throw MissingSchemaError: Schema hasn't been registered for model "Password".
since the model Password
haven't been setup at this point:
const Password = mongoose.connection.model('Password');
So I tried adding --require ./index.js
before the --recursive
option, this indeed loads other files before passwords.controller.js
but the latter still runs before index.js
have even finished.
The solutions here doesn't work because index.js
doesn't run first.
How can I modify my test
script to allow my index.js
to finish before I run any test files?