Skip to main content

Command Palette

Search for a command to run...

JEST Hooks

Published
View as Markdown
  1. 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.

  2. 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
     });
    
  3. 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
     });
    
  4. 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
     });
    
  5. 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
     });
    
  6. 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