Introduction to Jest
What is Jest?
Jest is a delightful JavaScript testing framework maintained by Facebook, designed to ensure correctness in any JavaScript codebase. It is widely used for testing React applications but can also be utilized for testing any JavaScript project.
- Zero configuration: Jest aims to work out of the box for most JavaScript projects.
- Fast and safe: Tests run in parallel, and Jest uses a smart test runner.
- Snapshot testing: Useful for testing React components.
Installation
To install Jest, you can use npm or yarn. Run one of the following commands in your project directory:
npm install --save-dev jest
yarn add --dev jest
Basic Usage
Create a test file with a .test.js
or .spec.js
extension. For example, create a file named sum.test.js
:
function sum(a, b) {
return a + b;
}
module.exports = sum;
Next, add the following test to sum.test.js
:
const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
Run your tests using:
npx jest
Test Structure
Jest tests are structured with three main functions:
describe()
: Groups related tests.test()
orit()
: Defines a single test case.expect()
: Contains the assertion.
Example:
describe('sum function', () => {
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
});
Best Practices
To write effective tests, consider the following best practices:
- Keep tests isolated and independent.
- Name your tests clearly and descriptively.
- Use beforeEach() and afterEach() for setup and teardown.
- Utilize snapshot testing for UI components.
FAQ
What does Jest use for assertion?
Jest uses an assertion library called Jasmine. It allows you to use functions like expect()
to create assertions.
Can I use Jest for testing non-JavaScript files?
Jest is primarily designed for JavaScript. However, you can integrate it with other tools to test other files or formats.
How do I run tests in watch mode?
You can run Jest in watch mode by using the command npx jest --watch
. This will rerun tests on file changes.