mirror of
https://github.com/Fechin/reference.git
synced 2026-11-20 21:23:11 +03:00
feat(docs): add comprehensive Jest & React Testing Library cheat sheet
This commit is contained in:
commit
2f5acb2ac0
2 files changed
+624
No files matched your search
@@ -0,0 +1,314 @@
|
||||
---
|
||||
title: Jest Cheat Sheet
|
||||
date: 2022-09-09 00:00:00
|
||||
background: bg-blue-500
|
||||
description: A complete cheat sheet on Jest for testing React applications effectively.
|
||||
tags: React
|
||||
Testing
|
||||
Jest
|
||||
categories:
|
||||
- Testing
|
||||
intro:
|
||||
Jest is a JavaScript testing framework designed by Facebook. It works out of the box with modern
|
||||
JavaScript apps especially those built with React or Node.js. Its main goal is to simplify testing by providing all required features in one package test runner, assertion library, mocking, spies, coverage reports, and snapshot testing.
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## A Quick Overview to Jest
|
||||
|
||||
Jest is a delightful JavaScript testing framework maintained by Facebook. It is widely used for **unit testing**, **integration testing**, and even **end-to-end testing** in modern JavaScript and Node.js applications. Jest comes with a powerful set of features, including a built-in test runner, assertion library, mocking utilities, snapshot testing, and test coverage reporting.
|
||||
|
||||
This guide targets **Jest v20** and gives a concise yet practical overview of how to use it effectively.
|
||||
|
||||
### Key Concepts Explained
|
||||
|
||||
- **`describe()`**: Used to group related test cases into a test suite.
|
||||
- **`test()` / `it()`**: Define a single test case. `it()` is just a BDD-style alias for `test()`.
|
||||
- **`expect()`**: Assertion library that checks whether a value meets expectations.
|
||||
- **`beforeEach()` / `afterEach()`**: Runs code before or after every test in a suite.
|
||||
- **`beforeAll()` / `afterAll()`**: Runs setup/teardown code once before or after all tests.
|
||||
- **`.only` / `.skip`**: Focus or ignore specific tests/suites.
|
||||
- **Snapshot testing**: Captures the rendered output and compares it across test runs.
|
||||
- **Mock functions**: Simulate function behavior or monitor how functions are called.
|
||||
- **Timer mocks**: Test time-based behavior like `setTimeout()` and `setInterval()`.
|
||||
- **Async testing**: Write tests that handle Promises or `async/await`.
|
||||
|
||||
---
|
||||
|
||||
### 🚀 Quick Start
|
||||
|
||||
```bash
|
||||
npm install --save-dev jest babel-jest
|
||||
```
|
||||
|
||||
Add this to your `package.json`:
|
||||
|
||||
```json
|
||||
"scripts": {
|
||||
"test": "jest"
|
||||
}
|
||||
```
|
||||
|
||||
Run your tests:
|
||||
|
||||
```bash
|
||||
npm test -- --watch
|
||||
```
|
||||
|
||||
📖 See: [Getting Started](https://jestjs.io/docs/getting-started)
|
||||
|
||||
---
|
||||
|
||||
## ✍️ Writing Tests
|
||||
|
||||
```js
|
||||
describe('My work', () => {
|
||||
test('works', () => {
|
||||
expect(2).toEqual(2);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- **describe**: Group related tests.
|
||||
- **test** or **it**: Define individual test cases.
|
||||
- **expect**: Make assertions.
|
||||
|
||||
🔄 `it()` is an alias for `test()`.
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Setup Hooks
|
||||
|
||||
Use these for setup/teardown routines:
|
||||
|
||||
```js
|
||||
beforeEach(() => { ... });
|
||||
afterEach(() => { ... });
|
||||
beforeAll(() => { ... });
|
||||
afterAll(() => { ... });
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Focusing or Skipping Tests
|
||||
|
||||
**Focusing tests:**
|
||||
|
||||
```js
|
||||
describe.only(...);
|
||||
it.only(...); // or fit()
|
||||
```
|
||||
|
||||
**Skipping tests:**
|
||||
|
||||
```js
|
||||
describe.skip(...);
|
||||
it.skip(...); // or xit()
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🏁 Optional CLI Flags
|
||||
|
||||
| Flag | Description |
|
||||
| --------------------- | --------------------------------------- |
|
||||
| `--coverage` | Show test coverage summary |
|
||||
| `--detectOpenHandles` | Detect unclosed handles (e.g., sockets) |
|
||||
| `--runInBand` | Run tests serially (useful for CI) |
|
||||
|
||||
---
|
||||
|
||||
## ✅ Expectations (Matchers)
|
||||
|
||||
### Basic
|
||||
|
||||
```js
|
||||
expect(value).not.toBe(value);
|
||||
expect(value).toEqual(value);
|
||||
expect(value).toBeTruthy();
|
||||
```
|
||||
|
||||
> Note: `toEqual` performs deep equality.
|
||||
|
||||
### Snapshots
|
||||
|
||||
```js
|
||||
expect(value).toMatchSnapshot();
|
||||
expect(value).toMatchInlineSnapshot();
|
||||
```
|
||||
|
||||
> Inline snapshots require Prettier.
|
||||
|
||||
### Errors
|
||||
|
||||
```js
|
||||
expect(fn).toThrow(error);
|
||||
expect(fn).toThrowErrorMatchingSnapshot();
|
||||
```
|
||||
|
||||
### Booleans
|
||||
|
||||
```js
|
||||
expect(value).toBeFalsy();
|
||||
expect(value).toBeNull();
|
||||
expect(value).toBeTruthy();
|
||||
expect(value).toBeUndefined();
|
||||
expect(value).toBeDefined();
|
||||
```
|
||||
|
||||
### Numbers
|
||||
|
||||
```js
|
||||
expect(value).toBeCloseTo(number, digits);
|
||||
expect(value).toBeGreaterThan(number);
|
||||
expect(value).toBeLessThanOrEqual(number);
|
||||
```
|
||||
|
||||
### Objects
|
||||
|
||||
```js
|
||||
expect(value).toBeInstanceOf(Class);
|
||||
expect(value).toMatchObject(obj);
|
||||
expect(value).toHaveProperty('key', value);
|
||||
```
|
||||
|
||||
### Arrays/Strings
|
||||
|
||||
```js
|
||||
expect(value).toContain(item);
|
||||
expect(value).toHaveLength(number);
|
||||
expect(value).toMatch(/pattern/);
|
||||
```
|
||||
|
||||
### Custom Matchers
|
||||
|
||||
```js
|
||||
expect.extend(customMatchers);
|
||||
expect.any(Constructor);
|
||||
expect.assertions(1);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ⏱️ Async Tests
|
||||
|
||||
### Promises
|
||||
|
||||
```js
|
||||
test('resolves correctly', () => {
|
||||
return somePromise().then(data => {
|
||||
expect(data).toEqual(...);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Async/Await
|
||||
|
||||
```js
|
||||
test('awaits correctly', async () => {
|
||||
const result = await asyncFunc();
|
||||
expect(result).toBe(...);
|
||||
});
|
||||
```
|
||||
|
||||
📖 See: [Jest Async Testing](https://jestjs.io/docs/asynchronous)
|
||||
|
||||
---
|
||||
|
||||
## 📸 Snapshot Testing
|
||||
|
||||
```js
|
||||
it('renders correctly', () => {
|
||||
const output = something();
|
||||
expect(output).toMatchSnapshot();
|
||||
});
|
||||
```
|
||||
|
||||
For React components:
|
||||
|
||||
```js
|
||||
import renderer from 'react-test-renderer';
|
||||
|
||||
it('matches snapshot', () => {
|
||||
const tree = renderer.create(<Component />).toJSON();
|
||||
expect(tree).toMatchSnapshot();
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ⏲️ Timers
|
||||
|
||||
```js
|
||||
jest.useFakeTimers();
|
||||
|
||||
it('delays call', () => {
|
||||
jest.runOnlyPendingTimers();
|
||||
jest.runAllTimers();
|
||||
});
|
||||
```
|
||||
|
||||
📖 See: [Timer Mocks](https://jestjs.io/docs/timer-mocks)
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Mock Functions
|
||||
|
||||
### Creating Mocks
|
||||
|
||||
```js
|
||||
const fn = jest.fn();
|
||||
const squared = jest.fn((n) => n * n);
|
||||
```
|
||||
|
||||
### Assertions
|
||||
|
||||
```js
|
||||
expect(fn).toHaveBeenCalled();
|
||||
expect(fn).toHaveBeenCalledTimes(2);
|
||||
expect(fn).toHaveBeenCalledWith(arg1, arg2);
|
||||
```
|
||||
|
||||
### Flexible Matchers
|
||||
|
||||
```js
|
||||
expect(fn).toHaveBeenCalledWith(expect.any(String));
|
||||
expect(fn).toHaveBeenCalledWith(expect.arrayContaining([1, 2]));
|
||||
```
|
||||
|
||||
### Instances
|
||||
|
||||
```js
|
||||
const MyClass = jest.fn();
|
||||
const a = new MyClass();
|
||||
const b = new MyClass();
|
||||
MyClass.mock.instances; // [a, b]
|
||||
```
|
||||
|
||||
### Call Data
|
||||
|
||||
```js
|
||||
fn.mock.calls.length;
|
||||
fn.mock.calls[0][0];
|
||||
```
|
||||
|
||||
### Return Values
|
||||
|
||||
```js
|
||||
jest.fn().mockReturnValue('hello');
|
||||
jest.fn().mockReturnValueOnce('hi');
|
||||
```
|
||||
|
||||
### Mock Implementations
|
||||
|
||||
```js
|
||||
const fn = jest
|
||||
.fn()
|
||||
.mockImplementationOnce(() => 1)
|
||||
.mockImplementationOnce(() => 2);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
This comprehensive guide helps you get started with Jest testing or use it like a pro. It pairs perfectly with the React Testing Library for a user-centric testing workflow.
|
||||
@@ -0,0 +1,310 @@
|
||||
---
|
||||
title: 'React Testing Library Cheat Sheet'
|
||||
date: 2022-09-09 00:00:00
|
||||
background: bg-blue-500
|
||||
tags:
|
||||
- react
|
||||
- testing
|
||||
- javascript
|
||||
- cheatsheet
|
||||
|
||||
categories:
|
||||
- Testing
|
||||
|
||||
intro: |
|
||||
When it comes to testing React apps manually, we can either choose to render individual component trees in a simplified test environment or run the complete app in a realistic browser environment (end-to-end testing). But for automated tests, React Testing Library (RTL) is recommended for its user-centric approach and maintainability.
|
||||
plugins:
|
||||
- copyCode
|
||||
---
|
||||
|
||||
## Introduction
|
||||
|
||||
React Testing Library is built on top of DOM Testing Library to test React components by querying and interacting with real DOM nodes, avoiding reliance on implementation details.
|
||||
|
||||
## Basic level
|
||||
|
||||
### 1. Purpose & Solution
|
||||
|
||||
RTL addresses maintainability by focusing on user-visible behavior:
|
||||
|
||||
- Tests run in actual DOM nodes.
|
||||
- Queries mirror user interactions.
|
||||
- `data-testid` as an escape hatch when needed.
|
||||
- Encourages accessibility.
|
||||
|
||||
### 2. A basic component render test
|
||||
|
||||
**Component (App.js):**
|
||||
|
||||
```js
|
||||
const title = 'Hello, World!';
|
||||
|
||||
function App() {
|
||||
return <div>{title}</div>;
|
||||
}
|
||||
|
||||
export default App;
|
||||
```
|
||||
|
||||
**Test (App.test.js):**
|
||||
|
||||
```js
|
||||
import { render } from '@testing-library/react';
|
||||
import App from './App';
|
||||
|
||||
describe('App', () => {
|
||||
test('renders App component', () => {
|
||||
render(<App />);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
Add debug to inspect output:
|
||||
|
||||
```js
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import App from './App';
|
||||
|
||||
describe('App', () => {
|
||||
test('renders App component', () => {
|
||||
render(<App />);
|
||||
screen.debug();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
Output in console:
|
||||
|
||||
```html
|
||||
<body>
|
||||
<div>
|
||||
<div>Hello, World!</div>
|
||||
</div>
|
||||
</body>
|
||||
```
|
||||
|
||||
### 3. Why use RTL vs Enzyme?
|
||||
|
||||
1. Tests based on user interactions, not internal APIs.
|
||||
2. Improves maintainability after refactors.
|
||||
3. Intuitive syntax (`getByText`, `getByAltText`, etc.).
|
||||
|
||||
### 4. Queries in RTL
|
||||
|
||||
```js
|
||||
import { render, screen } from '@testing-library/react';
|
||||
|
||||
test('should show login form', () => {
|
||||
render(<Login />);
|
||||
const input = screen.getByLabelText('Username');
|
||||
// events & assertions
|
||||
});
|
||||
```
|
||||
|
||||
**Single element queries:**
|
||||
|
||||
- `getBy*`: throws if none found
|
||||
- `queryBy*`: returns null if none
|
||||
- `findBy*`: async Promise
|
||||
|
||||
**Multiple elements queries:**
|
||||
|
||||
- `getAllBy*`: throws if none
|
||||
- `queryAllBy*`: returns \[] if none
|
||||
- `findAllBy*`: async Promise array
|
||||
|
||||
### 5. Component tree testing level
|
||||
|
||||
- Test at user interaction level, not per individual child component unless needed.
|
||||
|
||||
## Intermediate level
|
||||
|
||||
### 1. Jest vs RTL
|
||||
|
||||
- **Jest**: Test runner & assertion library (`describe`, `test`, `expect`).
|
||||
- **RTL**: DOM utilities for React; works within Jest (or other runners).
|
||||
|
||||
### 2. Mocking with MSW
|
||||
|
||||
```js
|
||||
// fetch.test.jsx
|
||||
import React from 'react';
|
||||
import { rest } from 'msw';
|
||||
import { setupServer } from 'msw/node';
|
||||
import { render, fireEvent, waitFor, screen } from '@testing-library/react';
|
||||
import '@testing-library/jest-dom';
|
||||
import Fetch from '../fetch';
|
||||
|
||||
const server = setupServer(
|
||||
rest.get('/greeting', (req, res, ctx) =>
|
||||
res(ctx.json({ greeting: 'hello there' }))
|
||||
)
|
||||
);
|
||||
|
||||
beforeAll(() => server.listen());
|
||||
afterEach(() => server.resetHandlers());
|
||||
afterAll(() => server.close());
|
||||
|
||||
test('loads and displays greeting', async () => {
|
||||
render(<Fetch url="/greeting" />);
|
||||
fireEvent.click(screen.getByText('Load Greeting'));
|
||||
await waitFor(() => screen.getByRole('heading'));
|
||||
expect(screen.getByRole('heading')).toHaveTextContent('hello there');
|
||||
expect(screen.getByRole('button')).toBeDisabled();
|
||||
});
|
||||
|
||||
test('handles server error', async () => {
|
||||
server.use(rest.get('/greeting', (req, res, ctx) => res(ctx.status(500))));
|
||||
render(<Fetch url="/greeting" />);
|
||||
fireEvent.click(screen.getByText('Load Greeting'));
|
||||
await waitFor(() => screen.getByRole('alert'));
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Oops, failed to fetch!');
|
||||
expect(screen.getByRole('button')).not.toBeDisabled();
|
||||
});
|
||||
```
|
||||
|
||||
### 3. `render` options
|
||||
|
||||
```js
|
||||
import { render } from '@testing-library/react';
|
||||
import '@testing-library/jest-dom';
|
||||
|
||||
test('renders a message', () => {
|
||||
const table = document.createElement('table');
|
||||
const { container } = render(<TableBody {...props} />, {
|
||||
container: document.body.appendChild(table),
|
||||
baseElement: document.body,
|
||||
hydrate: true,
|
||||
legacyRoot: true,
|
||||
queries: {
|
||||
/* custom queries */
|
||||
}
|
||||
});
|
||||
expect(container).toBeInTheDocument();
|
||||
});
|
||||
```
|
||||
|
||||
### 4. `renderHook` usage
|
||||
|
||||
```js
|
||||
import { renderHook } from '@testing-library/react';
|
||||
|
||||
test('returns logged in user', () => {
|
||||
const { result, rerender } = renderHook(
|
||||
({ name } = {}) => useLoggedInUser(name),
|
||||
{ initialProps: { name: 'Alice' } }
|
||||
);
|
||||
expect(result.current).toEqual({ name: 'Alice' });
|
||||
rerender({ name: 'Bob' });
|
||||
expect(result.current).toEqual({ name: 'Bob' });
|
||||
});
|
||||
```
|
||||
|
||||
## Advanced Level
|
||||
|
||||
### 1. Adding custom queries
|
||||
|
||||
```js
|
||||
const dom = require('@testing-library/dom');
|
||||
const { queryHelpers, buildQueries } = require('@testing-library/react');
|
||||
|
||||
// Override testId attribute
|
||||
export const queryByTestId = queryHelpers.queryByAttribute.bind(
|
||||
null,
|
||||
'data-test-id'
|
||||
);
|
||||
export const queryAllByTestId = queryHelpers.queryAllByAttribute.bind(
|
||||
null,
|
||||
'data-test-id'
|
||||
);
|
||||
export function getAllByTestId(container, id, ...rest) {
|
||||
const els = queryAllByTestId(container, id, ...rest);
|
||||
if (!els.length)
|
||||
throw queryHelpers.getElementError(
|
||||
`No element with [data-test-id="${id}"]`,
|
||||
container
|
||||
);
|
||||
return els;
|
||||
}
|
||||
export function getByTestId(container, id, ...rest) {
|
||||
const els = getAllByTestId(container, id, ...rest);
|
||||
if (els.length > 1)
|
||||
throw queryHelpers.getElementError(
|
||||
`Multiple elements with [data-test-id="${id}"]`,
|
||||
container
|
||||
);
|
||||
return els[0];
|
||||
}
|
||||
```
|
||||
|
||||
Or using `buildQueries`:
|
||||
|
||||
```js
|
||||
const queryAllByDataCy = (...args) =>
|
||||
queryHelpers.queryAllByAttribute('data-cy', ...args);
|
||||
const [
|
||||
queryByDataCy,
|
||||
getAllByDataCy,
|
||||
getByDataCy,
|
||||
findAllByDataCy,
|
||||
findByDataCy
|
||||
] = buildQueries(
|
||||
queryAllByDataCy,
|
||||
(c, v) => `Found multiple elements with data-cy="${v}"`,
|
||||
(c, v) => `Unable to find element with data-cy="${v}"`
|
||||
);
|
||||
```
|
||||
|
||||
### 2. Skipping auto cleanup
|
||||
|
||||
- Via CLI: `cross-env RTL_SKIP_AUTO_CLEANUP=true jest`
|
||||
- Or add to Jest `setupFiles`: `import '@testing-library/react/dont-cleanup-after-each';`
|
||||
|
||||
### 3. Migrating from Enzyme
|
||||
|
||||
1. Install RTL & jest-dom.
|
||||
2. Replace `shallow`/`mount` with `render` + `screen`.
|
||||
3. Migrate tests incrementally.
|
||||
|
||||
### 4. Querying within elements
|
||||
|
||||
```js
|
||||
import { render, within } from '@testing-library/react';
|
||||
|
||||
const { getByText } = render(<MyComponent />);
|
||||
const section = getByText('messages');
|
||||
const hello = within(section).getByText('hello');
|
||||
```
|
||||
|
||||
### 5. Integration testing
|
||||
|
||||
```js
|
||||
import { render, cleanup, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import nock from 'nock';
|
||||
import App from '../App';
|
||||
|
||||
const REPOS = [{ name: 'repo1', description: '...' }];
|
||||
|
||||
beforeAll(() =>
|
||||
nock('https://api.github.com')
|
||||
.persist()
|
||||
.get('/users/alice/repos')
|
||||
.reply(200, REPOS)
|
||||
);
|
||||
afterEach(cleanup);
|
||||
|
||||
test('user sees public repos', async () => {
|
||||
render(<App />);
|
||||
userEvent.type(screen.getByPlaceholderText('Enter username'), 'alice');
|
||||
userEvent.click(screen.getByRole('button', { name: /submit/i }));
|
||||
await waitFor(() =>
|
||||
REPOS.forEach((r) => expect(screen.getByText(r.name)).toBeInTheDocument())
|
||||
);
|
||||
expect(screen.queryByText('Loading...')).toBeNull();
|
||||
});
|
||||
```
|
||||
|
||||
## Conclusion
|
||||
|
||||
This comprehensive cheat sheet covers basic to advanced RTL usage—rendering, querying, mocking, custom queries, and integration tests—to help you write robust, maintainable tests.
|
||||
Reference in new issue
Block a user