Testing with Jest: Comprehensive Guide
--
Table of Contents
- Introduction to Jest
- Installation and Setup
- Writing Your First Test
- Test Matchers
- Asynchronous Testing
- Testing React Components
- Snapshot Testing
- Mock Functions
- Conclusion
1. Introduction to Jest
Jest is a powerful JavaScript testing framework developed by Facebook. It’s known for its “zero-configuration” philosophy and is designed to work seamlessly with most JavaScript projects and frameworks, including React. With Jest, you can write tests with an approachable, familiar, and feature-rich API that gives you results quickly.
2. Installation and Setup
Before getting started with Jest, you need to install it. We can setup Jest for our javascript applications by running the following command in your terminal as below
npm install --save-dev jest
Next, you will have to set up a test script in your package.json
file:
{
"scripts": {
"test": "jest"
}
}
With this setup, you can now run your tests using npm test
3. Writing Your First Test
Let’s start by writing a simple test. Assume we have a function sum
in a file called sum.js
function sum(a, b) {
return a + b;
}
To test this function, create a new file in the same directory called sum.test.js
. Jest automatically recognizes .test.js
files as test files. In sum.test.js
, import the sum
function and write the test:
const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
You can now run this test with npm test
, and Jest will print this message if the test passes: PASS ./sum.test.js
4. Test Matchers
Jest uses matchers
to let you test values in different ways. The .toBe
matcher used above checks for exact equality. If you want to check the value of an object, you should use…