A unit test is an automated test that checks the behavior of a small unit of code, usually a function or a method. It runs on its own, is fast and does not depend on a database, internet or other systems.
How it works
A unit test usually follows three steps:
- Prepare: define the input data.
- Execute: call the function being tested.
- Verify: compare the result with the expected value.
If the result is different, the test fails and shows where the problem is. A project can have hundreds of unit tests that run in a few seconds.
When a function depends on something external, such as a payment API, you use a "mock", a fake substitute that simulates the response. This way the test stays isolated and predictable.
Practical example
You have a function that applies a discount to an order. A unit test in JavaScript, using Jest, would look like this:
const { aplicarDesconto } = require('./desconto');
test('aplica 10% de desconto', () => {
expect(aplicarDesconto(100, 10)).toBe(90);
});
test('não aceita desconto negativo', () => {
expect(() => aplicarDesconto(100, -5)).toThrow();
});If someone changes the function and breaks the rule, the test fails before the error reaches the customer.
What it's for
It is used to find bugs early, provide safety when changing code and document the expected behavior. It is the foundation of the TDD practice.
With code agents, unit tests are even more useful. The agent changes the code and runs the tests to see if anything broke. Without tests, you have to check everything by hand. You can also ask AI to write the tests, but review them: a test generated without criteria may just repeat the code, without checking anything useful.
Difference between unit test and integration test
A unit test looks at an isolated piece. The integration test checks if several pieces work together, for example the function, the database and the API. Unit tests are fast and cheap. Integration is slower, but catches errors that only appear in the connection between parts. A good project uses both.