Your First Test
Alright, let us stop talking about testing and actually write a test. I remember the first time I ran a test and saw that green checkmark. It felt like winning a tiny victory. Let me give you that same feeling right now.
We are going to use Jest because it is beginner-friendly and comes with everything you need out of the box. No complicated setup required.
Setting Up Your Project
First, make sure you have Node.js installed. Then create a new folder and initialize it.
// terminal
mkdir my-first-test
cd my-first-test
npm init -y
npm install --save-dev jest
Now open your package.json and add a test script.
// package.json
{
"scripts": {
"test": "jest"
}
}
Writing Your First Test
Create a file called sum.js and add a simple function. Then create sum.test.js next to it.
// sum.js
function sum(a, b) {
return a + b;
}
module.exports = sum;
// sum.test.js
const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
Now run npm test in your terminal. Jest looks for files ending in .test.js, runs them, and tells you what passed or failed.
Seeing It Pass
When you see that green text saying your test passed, that is your code telling you everything works as expected. If you change the expected value to 4, the test fails and you get a clear error message showing the difference.
That is the magic of testing. You define what success looks like, and Jest checks it for you every single time.
Try it Yourself →Key Takeaways
- Jest is a beginner-friendly testing framework that comes with everything built in
- Tests go in files ending with .test.js
- The test() function defines what you want to check
- expect().toBe() is how you assert the result
- Run tests with npm test and watch for green checkmarks