Testing individual units with Jest
Unit tests are the smallest and most foundational part of the testing pyramid, verifying the behavior of individual units of code in isolation, such as functions, methods, or components. These tests are quick to write and execute, offering immediate feedback to developers.
We’ll use Jest to write unit tests and integration tests in this book. Jest is a comprehensive JavaScript testing framework built by Facebook, with a strong focus on simplicity. It’s feature-rich and supports asynchronous testing, mocking, and snapshot testing, making it a great choice for React applications.
Writing your first test
Let’s write a simple test. Say you have an add
function in a file called math.ts
:
export function add(a: number, b: number) { return a + b; }
To test this function, you must create a math.test.ts
file in the same directory:
import { add } from './math'; test('add adds numbers correctly...