Simple JavaScript testing framework for browsers and node.js
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Jasmine's test execution environment management including configuration options, randomization settings, timeout controls, and execution flow customization.
Functions for accessing and managing the Jasmine test environment.
/**
* Get the current Jasmine environment instance
* @param options - Optional configuration for environment creation
* @returns Environment instance
*/
jasmine.getEnv(options?: { suppressLoadErrors?: boolean }): Environment;Usage Examples:
// Get the default environment
const env = jasmine.getEnv();
// Get environment with error suppression
const env = jasmine.getEnv({ suppressLoadErrors: true });
// Configure and execute tests
env.configure({
random: true,
seed: '12345'
});
env.execute();Methods for configuring test execution behavior.
interface Environment {
/**
* Configure the test environment with options
* @param options - Configuration options object
*/
configure(options: EnvConfig): void;
/**
* Execute the test suite
* @param runnableIds - Optional array of specific runnable IDs to execute
*/
execute(runnableIds?: string[]): void;
/**
* Add a reporter to receive test results
* @param reporter - Reporter instance
*/
addReporter(reporter: Reporter): void;
/**
* Remove a reporter
* @param reporter - Reporter instance to remove
*/
removeReporter(reporter: Reporter): void;
/**
* Set the order of spec execution
* @param order - Order function or 'random'
*/
randomizeTests(seed?: string): void;
/**
* Get configuration value
* @param key - Configuration key
* @returns Configuration value
*/
configuration(): EnvConfig;
}Usage Examples:
const env = jasmine.getEnv();
// Configure environment
env.configure({
random: true,
seed: '67890',
stopOnSpecFailure: false,
failSpecWithNoExpectations: true,
stopSpecOnExpectationFailure: false
});
// Add custom reporter
const customReporter = {
specDone: (result) => {
console.log(`Spec: ${result.fullName} - ${result.status}`);
}
};
env.addReporter(customReporter);
// Execute specific tests
env.execute(['spec-1', 'spec-2']);
// Get current configuration
const config = env.configuration();
console.log('Random execution:', config.random);Configuration object interface and available options.
interface EnvConfig {
/**
* Randomize the order of execution of specs (default: true)
*/
random?: boolean;
/**
* Seed for randomization (default: random)
* Can be string or number
*/
seed?: string | number;
/**
* Stop executing specs after the first failure (default: false)
*/
stopOnSpecFailure?: boolean;
/**
* Fail specs that have no expectations (default: false)
*/
failSpecWithNoExpectations?: boolean;
/**
* Stop executing a spec after the first expectation failure (default: false)
*/
stopSpecOnExpectationFailure?: boolean;
/**
* Hide disabled specs from results (default: false)
*/
hideDisabled?: boolean;
/**
* Spec filter function to determine which specs to run
*/
specFilter?: (spec: Spec) => boolean;
/**
* Promise timeout for async specs in milliseconds
*/
asyncTimeout?: number;
}Usage Examples:
// Conservative configuration for CI
jasmine.getEnv().configure({
random: false, // Deterministic order
stopOnSpecFailure: true, // Fail fast
failSpecWithNoExpectations: true, // Ensure all specs have assertions
stopSpecOnExpectationFailure: false
});
// Development configuration
jasmine.getEnv().configure({
random: true,
seed: Date.now().toString(), // Different seed each run
hideDisabled: true, // Hide disabled specs
asyncTimeout: 10000 // 10 second timeout for async
});
// Custom spec filtering
jasmine.getEnv().configure({
specFilter: (spec) => {
// Only run specs with 'integration' in the name
return spec.getFullName().includes('integration');
}
});Pre-defined constants for common configuration values.
/**
* Default timeout interval for asynchronous operations (5000ms)
*/
jasmine.DEFAULT_TIMEOUT_INTERVAL: number;
/**
* Maximum depth for pretty-printing nested objects (8 levels)
*/
jasmine.MAX_PRETTY_PRINT_DEPTH: number;
/**
* Maximum length for pretty-printing arrays (50 elements)
*/
jasmine.MAX_PRETTY_PRINT_ARRAY_LENGTH: number;
/**
* Maximum number of characters for pretty-printing (1000 chars)
*/
jasmine.MAX_PRETTY_PRINT_CHARS: number;Usage Examples:
// Check default values
console.log('Default timeout:', jasmine.DEFAULT_TIMEOUT_INTERVAL); // 5000
// Modify global constants (affects all pretty-printing)
jasmine.MAX_PRETTY_PRINT_DEPTH = 5;
jasmine.MAX_PRETTY_PRINT_ARRAY_LENGTH = 25;
jasmine.MAX_PRETTY_PRINT_CHARS = 500;
// Use in test timeouts
it('should handle slow operation', (done) => {
slowOperation(() => {
expect(true).toBe(true);
done();
});
}, jasmine.DEFAULT_TIMEOUT_INTERVAL * 2); // 10 second timeoutMethods for controlling which tests execute.
interface Environment {
/**
* Set a filter function to determine which specs run
* @param filterFn - Function that returns true for specs to run
*/
specFilter(filterFn: (spec: Spec) => boolean): void;
}Usage Examples:
const env = jasmine.getEnv();
// Run only specs containing 'unit' in their name
env.specFilter((spec) => {
return spec.getFullName().toLowerCase().includes('unit');
});
// Run specs based on custom metadata
env.specFilter((spec) => {
const suite = spec.parentSuite;
return suite && suite.description.includes('API');
});
// Complex filtering logic
env.specFilter((spec) => {
const fullName = spec.getFullName();
const isIntegration = fullName.includes('integration');
const isUnit = fullName.includes('unit');
const runIntegration = process.env.RUN_INTEGRATION === 'true';
return runIntegration ? isIntegration : isUnit;
});Methods for controlling test execution flow.
interface Environment {
/**
* Throw errors instead of just failing specs
* @param value - Whether to throw on expectation failure
*/
throwOnExpectationFailure(value: boolean): void;
/**
* Stop execution after first spec failure
* @param value - Whether to stop on first failure
*/
stopOnSpecFailure(value: boolean): void;
/**
* Set random seed for test execution order
* @param seed - Seed value for randomization
*/
seed(seed: string | number): void;
/**
* Enable or disable random execution order
* @param value - Whether to randomize execution
*/
randomizeTests(value: boolean): void;
}Usage Examples:
const env = jasmine.getEnv();
// For debugging - throw on first failure
env.throwOnExpectationFailure(true);
env.stopOnSpecFailure(true);
// Set specific seed for reproducible runs
env.seed('test-seed-123');
env.randomizeTests(true);
// Disable randomization for debugging
env.randomizeTests(false);Methods for hooking into environment lifecycle events.
interface Environment {
/**
* Add a callback to be called before all specs
* @param fn - Function to call
*/
beforeAll(fn: () => void | Promise<void>): void;
/**
* Add a callback to be called after all specs
* @param fn - Function to call
*/
afterAll(fn: () => void | Promise<void>): void;
}Usage Examples:
const env = jasmine.getEnv();
// Global setup
env.beforeAll(async () => {
console.log('Starting test suite...');
await setupTestDatabase();
await seedTestData();
});
// Global teardown
env.afterAll(async () => {
console.log('Test suite completed');
await cleanupTestDatabase();
await closeConnections();
});Interface for custom reporters that receive test results.
interface Reporter {
/** Called when Jasmine starts running */
jasmineStarted?(suiteInfo: SuiteInfo): void;
/** Called when a suite starts */
suiteStarted?(result: SuiteResult): void;
/** Called when a spec starts */
specStarted?(result: SpecResult): void;
/** Called when a spec is done */
specDone?(result: SpecResult): void;
/** Called when a suite is done */
suiteDone?(result: SuiteResult): void;
/** Called when Jasmine is done running */
jasmineDone?(runDetails: RunDetails): void;
}
interface SuiteInfo {
totalSpecsDefined: number;
}
interface RunDetails {
overallStatus: 'passed' | 'failed' | 'incomplete';
totalTime: number;
incompleteReason?: string;
}Usage Examples:
// Custom console reporter
const customReporter = {
jasmineStarted: (suiteInfo) => {
console.log(`Running ${suiteInfo.totalSpecsDefined} specs`);
},
specStarted: (result) => {
console.log(`Starting: ${result.fullName}`);
},
specDone: (result) => {
const status = result.status === 'passed' ? '✓' : '✗';
console.log(`${status} ${result.fullName}`);
if (result.status === 'failed') {
result.failedExpectations.forEach(failure => {
console.log(` Error: ${failure.message}`);
});
}
},
jasmineDone: (runDetails) => {
console.log(`Tests completed: ${runDetails.overallStatus}`);
console.log(`Total time: ${runDetails.totalTime}ms`);
}
};
jasmine.getEnv().addReporter(customReporter);interface Environment {
configure(options: EnvConfig): void;
execute(runnableIds?: string[]): void;
addReporter(reporter: Reporter): void;
removeReporter(reporter: Reporter): void;
specFilter(filterFn: (spec: Spec) => boolean): void;
randomizeTests(value: boolean): void;
seed(seed: string | number): void;
configuration(): EnvConfig;
}
interface EnvConfig {
random?: boolean;
seed?: string | number;
stopOnSpecFailure?: boolean;
failSpecWithNoExpectations?: boolean;
stopSpecOnExpectationFailure?: boolean;
hideDisabled?: boolean;
specFilter?: (spec: Spec) => boolean;
asyncTimeout?: number;
}
interface SuiteResult {
id: string;
description: string;
fullName: string;
status?: string;
properties?: { [key: string]: any };
}
interface SpecResult {
id: string;
description: string;
fullName: string;
status: 'passed' | 'failed' | 'pending';
failedExpectations: ExpectationResult[];
passedExpectations: ExpectationResult[];
pendingReason?: string;
properties?: { [key: string]: any };
}