Cheat sheet · Back end and data
Testing cheat sheet
The test types, the Arrange-Act-Assert pattern and the Jest and Vitest functions you reuse.
- Sections
- 5
- Items
- 24
- Area
- Back end and data
- Download
- PNG, PDF
Cheat sheet
Testing
The test types, the Arrange-Act-Assert pattern and the Jest and Vitest functions you reuse.
Test types
Unit- One function or class alone. Many, fast
Integration- Several parts together, for example code and a database
End to end- A real browser walks through the app. Few, slow
Smoke- A tiny check that the app starts and the main page works
A test (Jest or Vitest)
describe("cart", () => { ... })- Group related tests
it("adds an item", () => { ... })- One test
beforeEach(() => { ... })- Setup before every test
expect(total).toBe(30)- Same value
expect(obj).toEqual({ a: 1 })- Same content
expect(list).toContain("a")- The list has the item
expect(fn).toThrow()- It throws an error
await expect(p).resolves.toBe(1)- A promise gives this value
Mocks
const fn = vi.fn() / jest.fn()- A fake function that records its calls
expect(fn).toHaveBeenCalledWith(1)- It was called with 1
fn.mockReturnValue(5)- Make the fake return 5
vi.spyOn(obj, "method")- Watch a real method
React Testing Library
render(<Button />)- Draw the component
screen.getByRole("button", { name: /save/i })- Find it the way a user would
await userEvent.click(button)- Click it
expect(screen.getByText("Saved")).toBeInTheDocument()- Check what the user sees
Good habits
Arrange, Act, Assert- Set up, do one thing, check the result
One reason to fail- Each test checks one behaviour
Test behaviour, not internals- Refactors should not break tests
Red, Green, Refactor- TDD: write a failing test, make it pass, clean up
Remember
- A flaky test (sometimes passes, sometimes fails) is worse than no test. Fix it or remove it.
- Coverage shows what ran, not what is correct. Use it to find gaps, not as a score.
Learn it properly
A cheat sheet helps you remember. These lessons explain the ideas step by step, with examples.