A unit test is a small automatic test that checks one tiny piece of code — usually a single function or method — on its own, without a browser, a network, or a database. It runs in milliseconds, so a project can have thousands of them and run them on every change.

What makes a good unit test

  • Fast — runs in milliseconds, so you can run all of them constantly.
  • Isolated — tests one unit and nothing else; slow or unpredictable parts (network, clock, database) are replaced with simple stand-ins.
  • Repeatable — gives the same answer every time, on every machine.
  • Focused — fails for one clear reason, so the failure points straight at the problem.

The shape of a unit test

Most unit tests follow Arrange, Act, Assert: set up the inputs, run the code, then check the result.

function add(a, b) {
  return a + b;
}

test('adds two numbers', () => {
  // Arrange
  const a = 2;
  const b = 3;

  // Act
  const result = add(a, b);

  // Assert
  expect(result).toBe(5);
});

Unit tests are the base of the testing pyramid: many cheap, fast tests below fewer, slower browser tests. See the automatic testing pyramid for where each layer fits.