Did you know that according to a recent survey, developers spend a significant portion of their time debugging code? Wouldn’t it be more efficient to prevent a major portion of bugs in the first place?
Jest, a popular JavaScript testing framework, empowers you to write clear and concise tests, ensuring your code functions as expected.
Jest boasts a philosophy of “delightful JavaScript testing.” It strives to make the testing process streamlined and enjoyable, even for developers new to the world of test-driven development (TDD). Unlike some frameworks that require extensive configuration, Jest is known for its minimal setup. You can often start writing tests with minimal boilerplate code, allowing you to focus on the actual testing logic.
Beyond its speed and ease of use, Jest offers a variety of powerful features like:
Rich assertion library: Jest provides a comprehensive set of assertion methods, allowing you to verify the expected behavior of your code in a clear and concise manner.
Mocking capabilities: Simulate external dependencies or complex objects with ease using Jest’s built-in mocking features. This isolates your unit under test, ensuring a focused and reliable testing environment.
Snapshot testing: This innovative feature allows you to capture the visual output of UI components and compare them against future versions. This helps ensure that any UI changes don’t introduce unintended visual regressions.
Extensive test coverage: Jest offers seamless integration with popular code coverage tools, enabling you to visualize which parts of your codebase are covered by tests. This helps identify areas that might require additional testing and promotes a more comprehensive testing strategy.
So now that you have a vague idea of Jest and its features, let's learn by setting up and writing your first tests to make your understanding clear.
Prerequisites:
Basic knowledge of JavaScript
Node.js and npm/yarn are globally installed on your machine
A JavaScript Project
Setting up Jest
- Run this command to add jest to your project.
npm install --save-dev jest
2. Add the following section to your package.json
:
{
"scripts": {
"test": "jest"
}
}
and the setup is done, it's that simple.
Writing Your First Tests
Let’s get started by writing a test for a hypothetical function that adds two numbers. First, create a sum.js
file and add the code below:
function sum(a, b) {
return a + b;
}
module.exports = sum;
Then, create a file named sum.test.js
. This will contain our actual test:
const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
Let’s break down this test to make you understand it part by part:
const sum = require('./sum');
This line imports the sum
function from the sum.js
file. It's the function that will be tested.
test('adds 1 + 2 to equal 3', () => {
This line defines a test case using Jest’s test
function. The first argument is a string description of the test ("adds 1 + 2 to equal 3"), and the second argument is a callback function that contains the test logic.
expect(sum(1, 2)).toBe(3);
});
Inside the callback function, expect(sum(1, 2))
calls the sum
function with arguments 1
and 2
, and checks the result. The toBe(3)
matcher asserts that the result should be 3
. If the sum
function returns 3
, the test passes; otherwise, it fails.
And now to execute this, run yarn test
or npm test
and Jest will print this message in your terminal:
PASS ./sum.test.js
✓ adds 1 + 2 to equal 3 (5ms)
This summary shows the total number of tests which ran, and how many passed, failed, or were skipped. Each test suite and individual test is listed with a pass or fail status, and execution time in milliseconds. If any tests fail, Jest provides detailed error messages, including the expected and actual results, and a traceback to the failing line of code.
Other Basic Jest Features
Matchers
Jest provides various matchers to validate different types of values in your tests. Some common matchers include toBe
, toEqual
, and toContain
. See the example below to understand their usage:
test('object assignment', () => {
const data = { one: 1 };
data['two'] = 2;
expect(data).toEqual({ one: 1, two: 2 });
});
toEqual
: Used for checking the value of objects and arrays. It checks for deep equality, meaning all properties and nested objects must match.
Testing Asynchronous Code
Jest can handle asynchronous code, allowing you to test promises and async/await functions.
test('the data is peanut butter', async () => {
const data = await fetchData();
expect(data).toBe('peanut butter');
});
This test waits for fetchData
to resolve, then checks if the returned data is 'peanut butter'.
Mock Functions
Mock functions help you test the behavior of functions that depend on external resources.
test('mock function', () => {
const mockFn = jest.fn();
mockFn();
expect(mockFn).toHaveBeenCalled();
});
jest.fn()
: Creates a mock function. toHaveBeenCalled()
: Checks if the mock function was called at least once.
Test Suites
describe
is used to group related tests, making your test output more readable and organized.
describe('sum module', () => {
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
});
This groups the tests related to the ‘sum module’ together, making the output easier to understand.
Setup and Teardown
Using beforeEach
, afterEach
, beforeAll
, and afterAll
for Setup and Teardown Logic. These functions help you run setup and cleanup code around your tests.
beforeEach(() => {
// Initialization before each test
});
afterEach(() => {
// Cleanup after each test
});
beforeEach
: Runs a function before each test in a file ordescribe
block.afterEach
: Runs a function after each test in a file ordescribe
block.beforeAll
: Runs once before all tests in a file.afterAll
: Runs once after all tests in a file.
Conclusion
In conclusion, Jest offers a compelling combination of simplicity, speed, and powerful features, making it an ideal choice for writing robust and maintainable JavaScript tests. So, if you’re looking to elevate your development workflow and ensure the quality of your code, consider giving Jest a try. You won’t be disappointed.
Thank you for reading! If you have any feedback or notice any mistakes, please feel free to leave a comment below. I’m always looking to improve my writing and value any suggestions you may have. If you’re interested in working together or have any further questions, please don’t hesitate to reach out to me at fa1319673@gmail.com.