Language: JavaScript
Testing
Jest was created by Facebook to test React applications, but it has grown to support any JavaScript project. Its zero-configuration setup, powerful mocking capabilities, and snapshot testing features make it widely popular for testing modern web applications.
Jest is a delightful JavaScript testing framework with a focus on simplicity, correctness, and developer experience. It supports unit, integration, and snapshot testing for JavaScript and TypeScript projects.
npm install --save-dev jestyarn add --dev jestJest allows developers to write tests using simple syntax and run them in a fast and isolated environment. It supports features like mocks, spies, snapshot testing, code coverage, and parallel test execution.
function sum(a, b) {
return a + b;
}
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});Defines a simple unit test that verifies the sum function returns the correct result.
let counter = 0;
beforeEach(() => {
counter = 0;
});
test('counter starts at 0', () => {
expect(counter).toBe(0);
});Resets the counter before each test using `beforeEach`.
const myFunc = jest.fn();
myFunc('hello');
expect(myFunc).toHaveBeenCalledWith('hello');Demonstrates using Jest's `fn()` to create a mock function and assert it was called with specific arguments.
const user = { name: 'Alice', age: 25 };
test('user snapshot', () => {
expect(user).toMatchSnapshot();
});Uses snapshot testing to verify that the object structure does not change unexpectedly.
function fetchData() {
return Promise.resolve('peanut butter');
}
test('the data is peanut butter', async () => {
const data = await fetchData();
expect(data).toBe('peanut butter');
});Tests an asynchronous function using `async/await` syntax.
jest.mock('./api');
import { fetchData } from './api';
fetchData.mockResolvedValue('mocked data');Shows how to mock entire modules to control dependencies in tests.
Write small, focused tests for individual units of code.
Use mocks and spies to isolate the code under test.
Leverage snapshot testing for UI components and serializable objects.
Run tests in watch mode during development for faster feedback.
Organize test files alongside source files or in a __tests__ directory for clarity.