Skip to content

Unit Test

In one line

A unit test checks one small piece of code — typically a single function — independently, with all external dependencies replaced by mocks or stubs.

In simple words

A unit test is like testing one car part in isolation. Instead of testing the whole car, you take just the brake and test it by itself. You don't need the engine, wheels, or transmission — you simulate everything the brake needs and test only the brake's logic.

In code, a 'unit' is usually one function or method. You call it with specific inputs and check that it returns the correct output. Any external things it depends on (database, network, other functions) are replaced with fake versions called mocks.

Unit tests are fast (milliseconds), numerous, and should be the foundation of your test suite. They give you quick feedback: if a unit test fails, you know exactly which function is broken.

Example

javascript
// Function under test
function add(a, b) { return a + b; }

// Unit test
test('add returns sum of two numbers', () => {
  expect(add(2, 3)).toBe(5);
});

The test calls add() directly and checks the return value. No dependencies to mock.

How it works

  1. Identify the function or method to test.
  2. Set up any required inputs (Arrange phase).
  3. Call the function with those inputs (Act phase).
  4. Check the output matches expectations (Assert phase).
  5. Mock any external dependencies to keep the test isolated.

Common confusions

  • Confused with: Integration Test

    The difference: A unit test checks one function in isolation; an integration test checks multiple components working together.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary