81 lines
2.6 KiB
JavaScript
81 lines
2.6 KiB
JavaScript
'use strict';
|
||
|
||
/**
|
||
* Jest integration test setup.
|
||
* Uses an in-memory MongoDB instance (mongodb-memory-server) so tests run
|
||
* without any external database credentials or infrastructure.
|
||
*
|
||
* TOKEN_SECRET may optionally be set in the environment; a safe default
|
||
* is used when it is absent (tests only, never production).
|
||
*/
|
||
|
||
// Ensure NODE_ENV=test so application code skips production-only paths.
|
||
process.env.NODE_ENV = 'test';
|
||
// Provide a default token secret for JWT signing in tests.
|
||
if (!process.env.TOKEN_SECRET) {
|
||
process.env.TOKEN_SECRET = 'test-secret-not-for-production';
|
||
}
|
||
|
||
const { MongoMemoryServer } = require('mongodb-memory-server');
|
||
const mongoose = require('mongoose');
|
||
|
||
let mongod = null;
|
||
const MONGOMS_VERSION = process.env.MONGOMS_VERSION || '4.4.28';
|
||
|
||
/**
|
||
* Start the in-memory MongoDB server and connect mongoose.
|
||
* Call this inside beforeAll() in each test file.
|
||
*/
|
||
async function connectDB() {
|
||
if (mongoose.connection.readyState !== 0) return; // already connected
|
||
|
||
try {
|
||
mongod = await MongoMemoryServer.create({
|
||
binary: { version: MONGOMS_VERSION },
|
||
});
|
||
} catch (error) {
|
||
const runtimeHint = String(error.message).includes('libcrypto.so.1.1') || String(error.message).includes('libssl.so.1.1')
|
||
? 'This runner is missing OpenSSL 1.1 compatibility libraries required by MongoDB 4.4.'
|
||
: 'If this runner lacks AVX support, keep MONGOMS_VERSION pinned to a 4.4.x release.';
|
||
|
||
error.message = `${error.message}\nFailed to start mongodb-memory-server with MongoDB ${MONGOMS_VERSION}. ${runtimeHint}`;
|
||
throw error;
|
||
}
|
||
const uri = mongod.getUri();
|
||
|
||
mongoose.set('strictPopulate', false);
|
||
await mongoose.connect(uri, {
|
||
connectTimeoutMS: 15000,
|
||
socketTimeoutMS: 30000,
|
||
});
|
||
|
||
// Register all discriminators in the correct order (user → sub-types).
|
||
// Require-ordering matters – base model first.
|
||
require('../../model');
|
||
}
|
||
|
||
/**
|
||
* Disconnect mongoose and stop the in-memory server.
|
||
* Call this inside afterAll() in each test file.
|
||
*/
|
||
async function disconnectDB() {
|
||
await mongoose.disconnect();
|
||
if (mongod) {
|
||
await mongod.stop();
|
||
mongod = null;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Remove all documents from a collection.
|
||
* Call this inside beforeEach() / afterEach() to keep tests isolated.
|
||
*/
|
||
async function clearCollection(model) {
|
||
if (!model || typeof model.deleteMany !== 'function') {
|
||
throw new Error('clearCollection received an invalid model. Check that connectDB completed successfully before using test models.');
|
||
}
|
||
await model.deleteMany({});
|
||
}
|
||
|
||
module.exports = { connectDB, disconnectDB, clearCollection };
|