Jest: The Delightful JavaScript Testing Suite
“Jest is a JavaScript testing framework designed to ensure correctness of any JavaScript codebase.” — Jest Core Team
Jest is an easy-to-use testing suite that provides developers with powerful features that will save you time (and headaches) while debugging your code. In this article, we’ll learn the basics of why testing is important, how to get started, and explore some real-world coding examples.
The Importance of Testing
Testing is a crucial step in the development process. Well-written tests will allow you to catch errors early in the pipeline before deploying to production.
For example, imagine a company releases a new version of its app without thoroughly testing it.
Customers start reporting issues with the app, causing the company to have to go back to the development phase to troubleshoot the issues, resulting in lost revenue while taking a hit to their reputation.
On the other hand, if the company had implemented an “early and often” approach to testing and error handling, they could have caught these issues before impacting their users.
Types of Testing
Testing comes in a wide variety of flavors!
Not all projects require the full gamut of tests, but implementing some of the basics is an easy way to create an efficient workflow.
Here’s a list of the most common types of testing:
- Unit testing: Ensures individual units or components of a software application function correctly in isolation.
- Integration testing: Checks how different parts of the application work together, and tests the interactions between them.
- System testing: Evaluates the overall performance of the entire system, and ensures that it meets requirements.
- Acceptance testing: Checks if the application meets the user’s requirements and expectations.
- Regression testing: Ensures that new changes or additions do not break previously working code.
- Performance testing: Checks how the application performs under various loads and conditions, evaluates speed, scalability, and stability.
- Security testing: Checks the security of the application against attacks and ensures that user data is kept safe.
- End-to-end testing: Evaluates the entire user flow of an application, checking how different components work together.
Getting Started with Jest
To get started with Jest, you need to add it to your project using npm.
npm install — save-dev jest
After it’s installed, we can write our first unit test.
Let’s start by creating a javascript file called ‘example.js’, then add this code (don’t forget ‘module.exports = sum’ at the bottom):
const sum = (a, b) => {
if (a && b) {
return a + b;
} else {
return 'invalid numbers';
}
};
module.exports = sum
In Jest, tests are defined in files with the .test.js extension.
Let’s create a file called ‘example.test.js’ in the same directory as our example.js file — this is where we’ll add our test conditions.
Add the following code to example.test.js:
const sum = require('./example');
test('should return the sum of a + b', () => {
expect(sum(2, 2)).toBe(4);
});
First, we imported the example.js module using require, then we used the ‘test’ Jest function to add a simple test using the ‘expect’ method that Jest refers to as a “matcher.”
Pro Tip: You can use any string you’d like as the first argument of your test function — it’s best practice to clearly state the outcome using a phrase like “should do XYZ.”
This test checks whether the sum()
function returns the expected sum of two numbers. It passes two arguments to the sum()
function (2 and 2) and uses the expect()
method (called an assertion) to see if the result is equal to 4 using the toBe()
matcher.
To run your test, add this script to your package.json file:
{
"scripts": {
"test": "jest"
}
}
Open your terminal (make sure you’re in the same directory as your test files) then type npm test into the command line.
Jest will automatically find and run any test files in your project.
$npm test
Congrats! You passed your first test!
Now for the fun part… let’s make it FAIL.
It’s always important to test for a failing condition to make sure you’re getting the intended output.
Change the numbers of your sum function to be something you know will fail, for example:
test('should return the sum of a + b', () => {
expect(sum(2, 8)).toBe(4);
});
Run your test again and you’ll see that it doesn’t pass this time:
The results of the failed test provide detailed information about what went wrong, and suggestions for where you can look in your code to fix it.
Let’s try a couple more tests.
Next, add the following code to your example.test.js file:
test('should return a message that says invalid numbers', () => {
expect(sum(2)).toBe('invalid numbers');
});
This test checks whether the sum()
function correctly handles invalid input. It passes only one argument to the sum()
function (2) which should result in an error because sum()
requires two arguments.
It then uses the expect()
function to assert that the result is equal to the string 'invalid numbers' using the toBe()
matcher.
Let’s run this test and see if it works:
Great work!
Two tests down, one to go.
For the final test, let’s check against a more complex data type:
Add the following code to your test file:
test('should match object with passed in object', () => {
// assertion
const data = {
favoriteGameCharacter: 'Link',
favoriteGameTitle: 'Breath of the Wild'
};
expect(data).toEqual({
favoriteGameCharacter: 'Link',
favoriteGameTitle: 'Breath of the Wild'
});
});
This time we’re testing whether an object matches an expected object.
We created an object data
with two properties favoriteGameCharacter
and favoriteGameTitle
and then used the expect()
function to assert that the data
object is equal to the expected object with the same properties and values using the toEqual()
matcher.
Run the test one last time….
We did it, all tests are passing and we can confidently send our code off for review.
Summary
In this blog post, we covered the basics of testing, took a close look at how to use Jest with your JavaScript code, and created a coding example for how to write and run your first tests. We also discussed some of the most commonly used testing keywords to help you get started with writing effective tests for your projects.
You should now have a solid foundation for using Jest in your own applications while writing reliable tests that will save you time, money, and frustration! Learning the basics of testing would have saved me countless headaches during my bootcamp experience, and I hope this article will help you avoid that mistake.
Sources
https://en.wikipedia.org/wiki/Jest_(framework)
https://www.testim.io/blog/unit-testing-best-practices/