How to Use Jest in JavaScript for Testing
To use
Jest in JavaScript, first install it with npm install --save-dev jest. Then, write test files using test() or it() functions and run tests with the jest command in your terminal.Syntax
Jest uses simple functions to define tests:
test('description', () => { ... }): Defines a test case with a description and a function containing assertions.expect(value): Creates an expectation object to check values.toBe(expected): Checks if the value matches the expected value exactly.
javascript
test('adds 1 + 2 to equal 3', () => { expect(1 + 2).toBe(3); });
Example
This example shows a simple test for a function that adds two numbers. It demonstrates how to write a test and run it with Jest.
javascript
function sum(a, b) { return a + b; } test('sum adds two numbers correctly', () => { expect(sum(2, 3)).toBe(5); expect(sum(-1, 1)).toBe(0); });
Output
PASS ./sum.test.js
✓ sum adds two numbers correctly (3 ms)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 1.234 s
Common Pitfalls
Common mistakes when using Jest include:
- Not installing Jest as a dev dependency.
- Writing test files without the correct naming convention (e.g.,
.test.jsor.spec.js). - Forgetting to export functions to test from modules.
- Using asynchronous code without handling promises or async/await properly.
javascript
/* Wrong: test file named sum.js instead of sum.test.js */ function sum(a, b) { return a + b; } test('sum test', () => { expect(sum(1, 2)).toBe(3); }); /* Right: Rename file to sum.test.js and run jest */
Quick Reference
| Command | Description |
|---|---|
| npm install --save-dev jest | Install Jest as a development dependency |
| jest | Run all test files |
| test('desc', fn) | Define a test case |
| expect(value).toBe(expected) | Check if value equals expected |
| jest --watch | Run tests in watch mode for auto rerun |
Key Takeaways
Install Jest with npm and write test files ending with .test.js or .spec.js.
Use test() and expect() functions to write clear test cases.
Run tests using the jest command in your terminal.
Name test files correctly and export functions to test to avoid errors.
Handle asynchronous code properly in tests using async/await or promises.