agmission/Development/server/tests/integration/jest.setup.js
2026-04-29 09:40:51 -04:00

66 lines
1.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'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;
/**
* 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
mongod = await MongoMemoryServer.create();
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) {
await model.deleteMany({});
}
module.exports = { connectDB, disconnectDB, clearCollection };