SmartCodingTips

πŸ§ͺ Introduction to Jest

Jest is a popular JavaScript testing framework developed by Meta. It’s used for unit testing and works seamlessly with React, offering powerful features like mocking, snapshot testing, and easy configuration.


βš™οΈ 1. Installation

If you're using Create React App (CRA), Jest is pre-installed. Otherwise, install manually:


npm install --save-dev jest babel-jest @testing-library/react @testing-library/jest-dom

πŸ§ͺ 2. Writing a Basic Test

Create a file like sum.test.js:


// sum.js
export function sum(a, b) {
  return a + b;
}

// sum.test.js
import { sum } from './sum';

test('adds 2 + 3 to equal 5', () => {
  expect(sum(2, 3)).toBe(5);
});

πŸš€ 3. Running Tests

Run the tests using the following command:


npx jest

🧩 4. Common Matchers

  • toBe(value): Exact match
  • toEqual(object): Deep equality
  • toContain(item): Array includes item
  • toHaveLength(n): Array or string length
  • toThrow(): Expect a function to throw error

πŸ“Έ 5. Snapshot Testing

Automatically track component UI output:


import { render } from '@testing-library/react';
import MyComponent from './MyComponent';

test('renders correctly', () => {
  const { asFragment } = render(<MyComponent />);
  expect(asFragment()).toMatchSnapshot();
});

🎭 6. Mocking with Jest

Jest lets you mock functions, modules, and timers. Example:


const mockFn = jest.fn();
mockFn('hello');
expect(mockFn).toHaveBeenCalledWith('hello');

πŸ“‹ Summary

  • Jest is fast, powerful, and widely used in the React ecosystem.
  • Supports unit, integration, and snapshot testing.
  • Works great with React Testing Library.