- Introduction
In this section, we’ll focus on writing unit tests for our JavaScript code. Unit tests help ensure individual parts of your code work as expected. Our dynamic duo, Geek and Gal, will provide easy-to-understand and engaging explanations to guide us through this process.
So, we're gonna dive into writing unit tests! 💪
Yeah, I'm excited! But how do we get started?
First, we need a testing framework. For JavaScript,
Jest
is a popular choice. You can install it using npm or yarn!
To install Jest, simply run the following command in your terminal:
npm install --save-dev jest
Got it! Jest is installed. Now what?
Now, let's write a simple JavaScript function and create a test file to write our unit tests!
Here's a simple function that adds two numbers. Save it as
sum.js
.
function sum(a, b) {
return a + b;
}
module.exports = sum;
Next, create a test file called
sum.test.js
. In this file, we'll write a test case to check if our
sum
function works correctly!
const sum = require('./sum');
test('sum adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
So, we import the
sum
function and then use the
test
function to write a test case with a description and a callback function, right?
Exactly! In the callback function, we use
expect
to check the result of our
sum
function and a matcher like
toBe
to compare it with the expected value!
Finally, to run your tests, add the following script to your
package.json
file:
"scripts": {
"test": "jest"
}
Now, you can run your tests by typing
npm test
in your terminal. If everything is set up correctly, you should see a success message! 🎉
Awesome! I just ran the tests, and they passed! 😃
- Conclusion
Writing unit tests is an essential part of the development process to ensure your code works as expected. With Jest, you can easily write and run tests for your JavaScript code, helping you catch issues early and deliver a better product. Keep up the good work! 👍