• 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.
Gal Normal

So, we're gonna dive into writing unit tests! 💪

Geek Curious

Yeah, I'm excited! But how do we get started?

Gal Happy

First, we need a testing framework. For JavaScript, Jest is a popular choice. You can install it using npm or yarn!

  • Installing Jest
Gal Pleased

To install Jest, simply run the following command in your terminal:

npm install --save-dev jest
Geek Happy

Got it! Jest is installed. Now what?

Gal Happy

Now, let's write a simple JavaScript function and create a test file to write our unit tests!

  • Writing a Unit Test
Gal Pleased

Here's a simple function that adds two numbers. Save it as sum.js .

function sum(a, b) {
  return a + b;
}

module.exports = sum;
Gal Pleased

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);
});
Geek Curious

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?

Gal Happy

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!

  • Running Unit Tests
Gal Pleased

Finally, to run your tests, add the following script to your package.json file:

"scripts": {
  "test": "jest"
}
Gal Happy

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! 🎉

Geek Happy

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! 👍