DEV Community

David Chedrick
David Chedrick

Posted on • Updated on

Cats, Code, and Jest: Testing Your JavaScript Purrfectly

Hello ❀️, fellow cat-loving coders! 😺 Today, we'll be exploring the world of testing JavaScript with Jest. When it comes to software development, testing is often overlooked, especially in the hustle of coding boot camps and self learning. So lets do a quick intro into unit testing with Jest. Grab your cat (or a lovie) and let's get started!


Why Test Your JavaScript Code?

In an ideal world, our code would always work purrfectly, but we know that's not the case. πŸ™€ This is why we test our code, to catch bugs and ensure that our applications function as expected. Unit testing is a crucial part of this process, as it helps us verify individual components of our code in isolation. Jest is a popular testing library for JavaScript that allows us to write tests easily and efficiently.


Getting Started with Jest!

Installation

To get started, let's add Jest to our project. Open your terminal, navigate to your project folder, and run:

npm install --save-dev jest
Enter fullscreen mode Exit fullscreen mode

Configuration

Next, add a "test" script to your package.json file:

"scripts": {
  "test": "jest"
}
Enter fullscreen mode Exit fullscreen mode

Now, you're all set to start writing tests with Jest! πŸŽ‰


Creating Our First Test

Let's say we have a simple function that calculates the total number of kitty treats we need to buy. It's in a file called

treats.js:


function calculateTreats(kitties, treatsPerKitty) {
  return kitties * treatsPerKitty;
}

module.exports = calculateTreats;
Enter fullscreen mode Exit fullscreen mode

To test this function, create a new file in the same directory called treats.test.js. Inside this file, we'll write our first test:

treats.test.js:

const calculateTreats = require('./treats');

test('Calculate the total number of kitty treats', () => {
  const kitties = 5;
  const treatsPerKitty = 10;
  const expectedTotalTreats = 50;

  expect(calculateTreats(kitties, treatsPerKitty)).toBe(expectedTotalTreats);
});
Enter fullscreen mode Exit fullscreen mode

In this test, we're using the test function provided by Jest. The first argument is a string describing the test, and the second argument is a function containing the actual test.


Running Our Tests

To run our tests, simply execute the following command in your terminal:

npm test
Enter fullscreen mode Exit fullscreen mode

If all goes well, you should see a message like this:

PASS  ./treats.test.js
  βœ“ Calculate the total number of kitty treats (5 ms)
Enter fullscreen mode Exit fullscreen mode

Congratulations! You've just written and run your first Jest test! 🐾🐾🐾🐾


Lets look at some of those Jest functions:

The test() function is used to define a single unit test within your test suite. It takes two arguments:

  1. A string that describes the test's purpose. This description helps you and other developers understand what the test is meant to verify or accomplish. It's important to be clear and concise when writing test descriptions.
    In our example above we used the test description: 'Calculate the total number of kitty treats'.

  2. The second argument is a callback function that contains the test logic. We define the input values (kitties and treatsPerKitty), the expected result (expectedTotalTreats), and use Jest's expect() function with the toBe() matcher to verify that the output of our calculateTreats() function matches the expected result.

When you run your tests using npm test, Jest will execute each test() function defined in your test files, and report the results (whether they pass or fail) along with their descriptions. This makes it easier to identify and fix any issues that arise during testing.


The expect() function is used to assert that a certain value or condition is met within your test.
Recall that we have a simple function in treats.js that calculates the total number of kitty treats we need to buy.
In the test, we first import the calculateTreats function from treats.js. Then, we use the test() function to define our test. Inside the test function, we set up some input values (kitties and treatsPerKitty) and the expected result (expectedTotalTreats).

Now, let's focus on the expect() function:

We call expect() with the actual value, which is the result of invoking our calculateTreats() function with the input values kitties and treatsPerKitty. In this case, the actual value is calculateTreats(5, 10) which should equal 50.

The expect() function then returns an "expectation" object with various matchers. In our example, we use the .toBe() matcher to compare the actual value with the expected result (expectedTotalTreats). The .toBe() matcher checks if the actual value is strictly equal (===) to the expected value.

In this case, if calculateTreats(5, 10) is equal to 50, the test passes. If not, the test fails, and Jest will report the discrepancy, indicating that our calculateTreats() function may not be working as expected.


Other Common Matchers:

.toBe(): Checks if the actual value is strictly equal (===) to the expected value.

.toEqual(): Checks if the actual value is deeply equal to the expected value. Useful for comparing objects and arrays.

.toBeTruthy(): Checks if the actual value is truthy (i.e., not false, 0, null, undefined, NaN, or an empty string).

.toBeFalsy(): Checks if the actual value is falsy (i.e., one of the aforementioned false, 0, null, undefined, NaN, or an empty string).


Testing your JavaScript code with Jest can help you ensure that your applications are stable and reliable. By writing unit tests, you're investing in the long-term quality of your code, making it easier to maintain and improve. Plus, you'll have more time to cuddle with your favorite feline friends, knowing that your code is in tip-top shape! 🐱

Remember, a purrfectly tested codebase is a happy codebase.


Further Reading:
Jest Docs


❀️❀️❀️

Follow me on LinkedIn for future blog posts
May your code always be as graceful as a cat! 🐾

Top comments (0)