agmission/Development/server/tests/integration/jest.setup.js
Devin Major b46c995b3d
Some checks failed
Server Tests / Mocha – Unit & Utility Tests (push) Successful in 49s
Server Tests / Jest – Integration Tests (push) Failing after 1m17s
fix for build error running itests
2026-04-29 13:13:42 -04:00

78 lines
2.3 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;
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) {
error.message = `${error.message}\nFailed to start mongodb-memory-server with MongoDB ${MONGOMS_VERSION}. ` +
'If this runner lacks AVX support, keep MONGOMS_VERSION pinned to a 4.4.x release.';
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 };