JEST Hooks
Introduction
In the Jest testing framework, hooks are special functions that are used to perform specific actions at different stages of the testing lifecycle. They allow you to set up conditions before running tests and clean up afterwards.beforeAll(callback, timeout)
Runs once before all tests in the suite.
Useful for setup that only needs to be done once, such as initializing a database connection.
beforeAll(() => { // setup code here });afterAll(callback, timeout)
Runs once after all tests in the suite.
Useful for teardown that only needs to be done once, such as closing a database connection.
afterAll(() => { // teardown code here });beforeEach(callback, timeout)
Runs before each test in the suite.
Useful for setup that needs to be done before every test, such as resetting data.
beforeEach(() => { // setup code here });afterEach(callback, timeout)
Runs after each test in the suite.
Useful for cleanup that needs to be done after every test, such as clearing mocks.
afterEach(() => { // cleanup code here });Example
describe('My Test Suite', () => { beforeAll(() => { console.log('Run once before all tests'); // e.g., initialize database }); afterAll(() => { console.log('Run once after all tests'); // e.g., close database connection }); beforeEach(() => { console.log('Run before each test'); // e.g., reset test data }); afterEach(() => { console.log('Run after each test'); // e.g., clear mocks }); test('first test', () => { console.log('Running first test'); expect(true).toBe(true); }); test('second test', () => { console.log('Running second test'); expect(true).toBe(true); }); });// output Run once before all tests Run before each test Running first test Run after each test Run before each test Running second test Run after each test Run once after all tests