agmission/Development/server/tests/integration/jest.setup.js
Devin Major 4dad304f86
Some checks failed
Server Tests / Mocha – Unit & Utility Tests (push) Successful in 48s
Server Tests / Jest – Integration Tests (push) Failing after 1m20s
fix bootstrapping of test data
2026-04-29 13:24:33 -04:00

110 lines
3.7 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 mailerMock = {
agmMailSig: ['Best,', 'AgMision Team'],
sendTestMail: jest.fn(async () => ({})),
sendMail: jest.fn(async () => ({})),
sendTextMail: jest.fn(async () => ({})),
sendAdminNotification: jest.fn(async () => ({})),
sendUpdatePaymentEmail: jest.fn(async () => ({})),
sendUpdateBillingAddressEmail: jest.fn(async () => ({})),
sendCurSubcriptionsEmail: jest.fn(async () => ({})),
sendSubTrialEndingRemindEmail: jest.fn(async () => ({})),
sendSubRenewalRemindEmail: jest.fn(async () => ({})),
sendTempCredential: jest.fn(async () => ({})),
sendPasswordResetEmail: jest.fn(async () => ({})),
sendResetPasswordEmail: jest.fn(async () => ({})),
validateEmailDelivery: jest.fn(async () => true),
sendEmailVerificationCode: jest.fn(async () => ({})),
sendWelcomeNewAccEmail: jest.fn(async () => ({})),
sendPromoExpiredEmail: jest.fn(async () => ({})),
withBaseUrl: jest.fn((value) => value),
};
jest.doMock(require.resolve('../../helpers/mailer'), () => mailerMock);
jest.mock('error-handler', () => ({
errorHandler: {
mailErrorToAdmin: jest.fn(async () => ({})),
},
}), { virtual: true });
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);
mongoose.set('strictQuery', 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 };