@pulzar/core
Version:
Next-generation Node.js framework for ultra-fast web applications with zero-reflection DI, GraphQL, WebSockets, events, and edge runtime support
234 lines • 6.58 kB
JavaScript
import { beforeAll, afterAll, beforeEach, afterEach } from "vitest";
import { logger } from "../utils/logger";
export class TestSetup {
config;
context = {};
constructor(config = {}) {
this.config = {
port: 0, // Use random port
timeout: 10000,
enableLogs: false,
cleanupAfterEach: true,
setupDatabase: false,
enableAuth: false,
...config,
};
}
/**
* Setup test environment
*/
async setup() {
try {
// Setup logging
if (!this.config.enableLogs) {
this.disableLogs();
}
// Initialize cleanup array
this.context.cleanup = [];
// Setup database if needed
if (this.config.setupDatabase) {
await this.setupDatabase();
}
// Create test app
this.context.app = await this.createTestApp();
// Start test server
await this.startTestServer();
logger.info("Test environment setup complete", {
port: this.context.port,
baseUrl: this.context.baseUrl,
});
return this.context;
}
catch (error) {
logger.error("Failed to setup test environment", { error });
throw error;
}
}
/**
* Cleanup test environment
*/
async cleanup() {
try {
// Run custom cleanup functions
if (this.context.cleanup) {
for (const cleanupFn of this.context.cleanup) {
await cleanupFn();
}
}
// Stop server
if (this.context.app) {
await this.context.app.close();
}
// Clear context
this.context = {};
logger.info("Test environment cleanup complete");
}
catch (error) {
logger.error("Failed to cleanup test environment", { error });
throw error;
}
}
/**
* Create test application
*/
async createTestApp() {
// This would typically create a test version of your app
// For now, create a minimal Fastify app
const fastify = require("fastify");
const app = fastify({ logger: this.config.enableLogs });
// Health check endpoint
app.get("/health", async (request, reply) => {
return { status: "ok", timestamp: new Date().toISOString() };
});
// Test endpoint
app.get("/test", async (request, reply) => {
return { message: "Test endpoint working" };
});
return app;
}
/**
* Start test server
*/
async startTestServer() {
if (!this.context.app) {
throw new Error("App not created");
}
try {
const address = await this.context.app.listen({
port: this.config.port,
host: "127.0.0.1",
});
// Parse the address to get port
const url = new URL(address);
this.context.port = parseInt(url.port);
this.context.baseUrl = `http://localhost:${this.context.port}`;
this.context.server = this.context.app.server;
}
catch (error) {
throw new Error(`Failed to start test server: ${error}`);
}
}
/**
* Setup test database
*/
async setupDatabase() {
// This would setup a test database
// For now, just add a cleanup function
this.context.cleanup?.push(async () => {
// Cleanup database
logger.debug("Cleaning up test database");
});
}
/**
* Disable logging for tests
*/
disableLogs() {
// Temporarily disable console methods
const originalMethods = {
log: console.log,
warn: console.warn,
error: console.error,
info: console.info,
};
console.log = () => { };
console.warn = () => { };
console.error = () => { };
console.info = () => { };
// Restore on cleanup
this.context.cleanup?.push(async () => {
console.log = originalMethods.log;
console.warn = originalMethods.warn;
console.error = originalMethods.error;
console.info = originalMethods.info;
});
}
/**
* Add custom cleanup function
*/
addCleanup(fn) {
if (!this.context.cleanup) {
this.context.cleanup = [];
}
this.context.cleanup.push(fn);
}
/**
* Get test context
*/
getContext() {
return this.context;
}
}
// Global test setup instance
let globalTestSetup = null;
/**
* Setup global test environment
*/
export async function setupTestEnvironment(config) {
if (globalTestSetup) {
return globalTestSetup.getContext();
}
globalTestSetup = new TestSetup(config);
return await globalTestSetup.setup();
}
/**
* Cleanup global test environment
*/
export async function cleanupTestEnvironment() {
if (globalTestSetup) {
await globalTestSetup.cleanup();
globalTestSetup = null;
}
}
/**
* Get current test context
*/
export function getTestContext() {
if (!globalTestSetup) {
throw new Error("Test environment not setup. Call setupTestEnvironment() first.");
}
return globalTestSetup.getContext();
}
/**
* Create a test suite with automatic setup/cleanup
*/
export function createTestSuite(config) {
let testSetup;
let context;
beforeAll(async () => {
testSetup = new TestSetup(config);
context = await testSetup.setup();
});
afterAll(async () => {
if (testSetup) {
await testSetup.cleanup();
}
});
beforeEach(async () => {
// Optional per-test setup
});
afterEach(async () => {
if (config?.cleanupAfterEach && testSetup) {
// Run cleanup after each test if configured
}
});
return {
getContext: () => context,
addCleanup: (fn) => testSetup?.addCleanup(fn),
};
}
/**
* Vitest global setup
*/
export async function globalSetup() {
await setupTestEnvironment({
enableLogs: false,
setupDatabase: true,
});
}
/**
* Vitest global teardown
*/
export async function globalTeardown() {
await cleanupTestEnvironment();
}
//# sourceMappingURL=setup.js.map