Jest - Special Testing Scenarios



In this chapter, we'll cover special scenarios you might face when writing tests with Jest. These scenarios will help you set up tests, manage test execution, and organize your tests more efficiently. They include:

Jest - Setup and Teardown

In testing, it's often necessary to set up certain conditions before tests run(setup) and clean up afterward(teardown). Jest provides special functions, called hooks, to handle this.

Global Setup and Teardown

Jest allows you to specify setup and teardown scripts that run before and after all the tests in the test suite.

  • Global Setup: Runs once before all tests are run.
  • Global Teardown: Runs once after all tests are finished.

You configure these scripts in jest.config.js:

module.exports = {
    globalSetup: './setup.js', // path to setup script
    globalTeardown: './teardown.js', // path to teardown script
};

Test Setup and Teardown

If you need to set up and tear down the environment for each individual test, you can use the beforeAll, afterAll, beforeEach, and afterEach hooks.

  • beforeAll: Runs once before all tests.
  • afterAll: Runs once after all tests.
  • beforeEach: Runs before each test.
  • afterEach: Runs after each test.

Example

beforeAll(() => {
    // Setup before all tests
});

afterAll(() => {
    // Cleanup after all tests
});

beforeEach(() => {
    // Setup before each test
});

afterEach(() => {
    // Cleanup after each test
});
These hooks help initialize and clean up any state or dependencies needed for your tests.

Jest - Before/After Hooks

Jest provides four hooks to help prepare your test environment:

beforeAll

This hook runs once before any tests in a test suite. It's perfect for setting up shared resources like database connections, mock APIs, etc.

beforeAll(() => {
    console.log('Before All Tests');
});

afterAll

This hook runs once after all tests are done. It is useful for cleaning up resources created in beforeAll.

afterAll(() => {
    console.log('After All Tests');
});

beforeEach

This hook runs before every individual test. It provides a fresh setup for each test and is commonly used to reset variables, mock implementations, or clean up shared states.

beforeEach(() => {
    console.log('Before Each Test');
});

afterEach

This hook runs after each test completes. It's often used to restore mocks, clear states, or clean up resources.

afterEach(() => {
    console.log('After Each Test');
});

Jest - Grouping Tests

Grouping tests is important for organizing test cases, especially in large files or with multiple related tests. Jest provides the describe block to group tests, helping to structure them logically and run specific groups when needed.

Using describe

The describe block is used to group tests that share a common setup or context. You can also nest describe() blocks to improve structure.

describe('Math operations', () => {
    describe('Addition', () => {
        test('should add numbers correctly', () => {
            expect(2 + 3).toBe(5);
        });
    });

    describe('Subtraction', () => {
        test('should subtract numbers correctly', () => {
            expect(5 - 3).toBe(2);
        });
    });
}); 

This groups tests into two main categories: Addition and Subtraction.

Nested describe() Blocks

You can also nest describe() blocks for more specific organization.

describe('User Login', () => {
    describe('with valid credentials', () => {
        test('should allow login', () => {
            expect(true).toBe(true);
        });
    });

    describe('with invalid credentials', () => {
        test('should reject login', () => {
            expect(false).toBe(false);
        });
    });
});

Jest - Skipping and Focusing Tests

Sometimes, you may want to temporarily skip a test (for debugging or development) or focus on a specific test. Jest provides .skip and .only to handle these situations.

Skipping Tests with .skip

If you want to skip a test or a whole test suite temporarily, you can use .skip. This prevents Jest from running the test, but it's still visible in the test output.

  • test.skip(): Skips an individual test.
  • describe.skip(): Skips all tests inside a specific describe block.
test.skip('this test is skipped', () => {
    expect(true).toBe(false);
});

Similarly, you can also skip a whole group of tests:

describe.skip('Math Operations', () => {
    test('adds numbers correctly', () => {
        expect(1 + 2).toBe(3);
    });
});

Focusing on a Specific Test with .only

If you want to run just one test or one group of tests, you can use .only to focus on it.

  • test.only(): Runs only this specific test.
  • describe.only(): Runs only the tests inside this describe block
test.only('this is the only test that runs', () => {
    expect(2 + 2).toBe(4);
});

You can also focus on an entire group of tests:

describe.only('Math Operations', () => {
    test('adds numbers correctly', () => {
        expect(1 + 2).toBe(3);
    });
});

Note: When using .only, Jest will run only the specified tests and skip the others. This is useful for debugging a specific part of your codebase.

Advertisements