Jest Global Setup for Database Initialization
This challenge focuses on implementing Jest's global setup functionality. You'll be tasked with creating a setup script that initializes a mock database before any tests run and a teardown script to clean it up afterward. This pattern is crucial for ensuring tests have a consistent and isolated environment, preventing side effects between test suites.
Problem Description
Your goal is to create a globalSetup.ts and globalTeardown.ts file for your Jest configuration.
What needs to be achieved:
- Global Setup: Implement a
globalSetupfunction that simulates initializing a database. This could involve tasks like creating tables, seeding initial data, or starting a mock server. - Global Teardown: Implement a
globalTeardownfunction that cleans up any resources created during the setup phase. This is essential for maintaining test isolation and preventing resource leaks. - Jest Configuration: Ensure your
jest.config.tscorrectly points to these setup and teardown files.
Key requirements:
- The
globalSetupscript should perform an action that signifies database initialization (e.g., logging a message to the console). - The
globalTeardownscript should perform an action that signifies database cleanup (e.g., logging a message to the console). - Your
jest.config.tsmust be updated to include theglobalSetupandglobalTeardownoptions. - You should create a simple test file (e.g.,
example.test.ts) to verify that the setup and teardown scripts are executed correctly.
Expected behavior: When Jest is run, you should see console output indicating that the global setup has occurred before any test output, and the global teardown has occurred after all test output.
Edge cases to consider:
- What happens if the setup script throws an error? (Jest will halt execution).
- What happens if the teardown script throws an error? (Jest will report the error, but tests will have already run).
Examples
Example 1:
Input: A Jest project with a `jest.config.ts` and a `globalSetup.ts` file.
Output (Console logs when running `jest`):
> Jest has been initialized.
> Running Test 1...
> Test 1 passed.
> Running Test 2...
> Test 2 passed.
> Jest has been torn down.
Explanation: This output shows the globalSetup message appearing first, followed by the test execution, and finally the globalTeardown message.
Example 2:
Input: A Jest project with `globalSetup.ts`, `globalTeardown.ts`, and `jest.config.ts` configured.
Content of `globalSetup.ts`:
module.exports = async () => {
console.log("Setting up mock database...");
// Simulate database initialization
await new Promise(resolve => setTimeout(resolve, 100)); // Simulate async operation
console.log("Mock database ready.");
};
Content of `globalTeardown.ts`:
module.exports = async () => {
console.log("Cleaning up mock database...");
// Simulate database cleanup
await new Promise(resolve => setTimeout(resolve, 50)); // Simulate async operation
console.log("Mock database cleaned up.");
};
Content of `jest.config.ts`:
module.exports = {
globalSetup: './globalSetup.ts',
globalTeardown: './globalTeardown.ts',
// ... other Jest configurations
};
Content of `example.test.ts`:
describe('Example Tests', () => {
test('should run after setup', () => {
console.log('Running Test 1...');
expect(true).toBe(true);
});
test('should run before teardown', () => {
console.log('Running Test 2...');
expect(1 + 1).toBe(2);
});
});
Output (Console logs when running `jest`):
> Setting up mock database...
> Mock database ready.
> Running Test 1...
> Test 1 passed.
> Running Test 2...
> Test 2 passed.
> Cleaning up mock database...
> Mock database cleaned up.
Explanation: This demonstrates how asynchronous operations within the setup and teardown scripts are handled, and how their console logs interleave with test execution logs.
Constraints
- The
globalSetupandglobalTeardownscripts must be written in TypeScript. - The
jest.config.tsfile must be used for Jest configuration. - Any asynchronous operations within setup/teardown should be handled using
async/await. - The solution should be runnable within a standard Node.js environment with Jest installed.
Notes
- Consider what kind of "setup" and "teardown" actions would be most representative of real-world scenarios (e.g., connecting to a database, starting/stopping mock servers, creating temporary files).
- Remember that
globalSetupandglobalTeardownfunctions receive aconfigobject as an argument, which contains the Jest configuration. You might find this useful for accessing environment variables or other configuration details. - The actual content of your mock database initialization and cleanup doesn't need to be complex; the focus is on demonstrating the correct implementation of Jest's global setup/teardown hooks.