У меня есть структура папок:
- 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
Мой индексный файл загружает приложение асинхронно:
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();
Мои тестовые файлы создаются следующим образом:
// 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', () => {
...
});
});
Я начинаю тесты так:
"test": "cross-env NODE_ENV=test ./node_modules/.bin/mocha --ui bdd --reporter spec --colors server --recursive --full-trace"
Вот где странность одолевает меня.В основном он загружает passwords.controller.js
до что-нибудь иначе, это из-за опции --recursive
.Этого не должно происходить, поскольку index.js
необходимо сначала загрузить, чтобы он мог подключиться к mongoose и т. Д. До начала любого из тестов, если этого не произойдет, этот фрагмент из passwords.controller.js
выдаст MissingSchemaError: Schema hasn't been registered for model "Password".
, поскольку модель Password
убежищеНа этом этапе не было настроено:
const Password = mongoose.connection.model('Password');
Поэтому я попытался добавить --require ./index.js
перед параметром --recursive
, он действительно загружает другие файлы до passwords.controller.js
, но последний все еще работает до того, как index.js
даже закончил.
Решения здесь не работает, потому что index.js
не запускается первым.
Как я могу изменить мой test
скрипт, чтобы мойindex.js
закончить, прежде чем запускать какие-либо тестовые файлы?