Jest is a JavaScript testing framework maintained by Meta (Facebook). It’s widely used for testing React applications, but it works with any JavaScript/TypeScript project.
It provides features like:
- Unit testing: testing small pieces of code (functions, components).
- Snapshot testing: ensuring UI doesn’t change unexpectedly.
- Mocking: simulating functions, APIs, or modules.
- Zero configuration: works out of the box for most setups.
Example: Testing a simple function
Let’s say you have a function sum.js
:
// sum.js
function sum(a, b) {
return a + b;
}
module.exports = sum;
Now, write a test for it in sum.test.js
:
// sum.test.js
const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
Running the test
If Jest is installed (npm install --save-dev jest
), add this to package.json
:
"scripts": {
"test": "jest"
}
Then run:
npm test
✅ Expected output:
PASS ./sum.test.js
✓ adds 1 + 2 to equal 3 (5 ms)