cs.oldnet

All sheets / Frontend & Testing

Jest

Unit testing syntax, mocking and the testing concepts interviewers ask about.

Structure

describe('cart', () => {
  beforeAll(() => {}); beforeEach(() => {});
  afterEach(() => jest.clearAllMocks());

  it('adds items', () => {
    expect(add([], 1)).toEqual([1]);
  });
  it.each([[1, 1, 2], [2, 2, 4]])('%i + %i = %i', (a, b, sum) => {
    expect(a + b).toBe(sum);
  });
  it.todo('handles discounts');
});

Matchers

MatcherChecks
toBeObject.is (primitives, same ref)
toEqual / toStrictEqualdeep equality (strict checks undefined props & class)
toBeTruthy / toBeNull / toBeUndefined
toContain / toHaveLengtharrays, strings
toMatchObjectsubset of props
toThrow(/msg/)wrap call: expect(() => fn()).toThrow()
toHaveBeenCalledWith(...) / toHaveBeenCalledTimes(n)mocks
expect.any(Number) / expect.objectContaining({})asymmetric

Async

test('resolves', async () => {
  await expect(fetchUser(1)).resolves.toMatchObject({ id: 1 });
  await expect(fetchUser(-1)).rejects.toThrow('not found');
});

Mocks

const fn = jest.fn().mockReturnValue(1).mockResolvedValueOnce({ ok: true });

jest.mock('./db');                       // auto-mock a module
import { query } from './db';
query.mockResolvedValue([{ id: 1 }]);

jest.mock('axios', () => ({ get: jest.fn() }));  // factory

const spy = jest.spyOn(service, 'send').mockImplementation(() => {});
spy.mockRestore();

clearAllMocks resets calls; resetAllMocks also resets implementations; restoreAllMocks restores spies.

Timers

jest.useFakeTimers();
debounced();
jest.advanceTimersByTime(300);
expect(fn).toHaveBeenCalled();
jest.useRealTimers();

React Testing Library

import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

render(<Login />);
await userEvent.type(screen.getByLabelText(/email/i), 'a@b.c');
await userEvent.click(screen.getByRole('button', { name: /sign in/i }));
expect(await screen.findByText(/welcome/i)).toBeInTheDocument();

Query priority: getByRole → getByLabelText → getByText → getByTestId. get throws, query returns null, find waits.

CLI & config

jest --watch
jest --coverage --coverageThreshold='{"global":{"lines":80}}'
jest -t "adds items"        # by test name
jest --ci --runInBand       # CI, serial

Testing concepts

  • Test pyramid: many unit, fewer integration, few E2E.
  • Mock vs stub vs spy vs fake: mock asserts interactions; stub returns canned data; spy wraps real; fake is a light working impl (in-memory DB).
  • AAA: Arrange, Act, Assert. One behaviour per test.
  • Snapshot tests catch unintended UI changes but are brittle; keep them small.
  • Flaky tests: shared state, real time/network, ordering. Isolate and fake them.