Unit Testing with Jest

Write robust unit tests for your JavaScript applications using Jest framework.

Admin • • 1 min read
Unit Testing with Jest
# Unit Testing with Jest Jest is the most popular testing framework for JavaScript. Let's learn how to write effective unit tests. ## Getting Started Install Jest in your project: ```bash npm install --save-dev jest ``` ## Basic Test Structure ```javascript describe('Calculator', () => { test('adds two numbers', () => { expect(add(2, 3)).toBe(5); }); test('subtracts two numbers', () => { expect(subtract(5, 3)).toBe(2); }); }); ``` ## Common Matchers ```javascript // Equality expect(value).toBe(4); expect(value).toEqual({ name: 'Alice' }); // Truthiness expect(value).toBeTruthy(); expect(value).toBeFalsy(); expect(value).toBeNull(); // Numbers expect(value).toBeGreaterThan(3); expect(value).toBeLessThan(5); // Strings expect(string).toMatch(/pattern/); // Arrays expect(array).toContain('item'); ``` ## Testing Async Code ```javascript test('fetches user data', async () => { const data = await fetchUser(1); expect(data.name).toBe('Alice'); }); ``` ## Mocking ```javascript jest.mock('./api'); test('calls API correctly', () => { const mockFetch = jest.fn(); api.fetch = mockFetch; fetchData(); expect(mockFetch).toHaveBeenCalledWith('/users'); }); ``` ## Testing React Components ```javascript import { render, screen } from '@testing-library/react'; test('renders button', () => { render(); expect(screen.getByText('Click me')).toBeInTheDocument(); }); ``` ## Best Practices 1. Test behavior, not implementation 2. Keep tests simple and focused 3. Use descriptive test names 4. Avoid test interdependence 5. Mock external dependencies Good tests give you confidence to refactor and add features. Write tests as you code!

You Might Also Like