How do you structure a typical Jest test file?

Beginner

Answer

A well-structured Jest test file typically follows this pattern:

// Import dependencies
import { functionToTest } from '../src/utils';

// Describe the module/component being tested
describe('functionToTest', () => {
  // Group related tests
  describe('when given valid input', () => {
    test('should return expected result', () => {
      // Arrange
      const input = 'test';
      
      // Act
      const result = functionToTest(input);
      
      // Assert
      expect(result).toBe('expected');
    });
  });
  
  describe('when given invalid input', () => {
    test('should throw an error', () => {
      expect(() => functionToTest(null)).toThrow();
    });
  });
});