0
0
NodejsHow-ToBeginner · 4 min read

How to Use Jest with Node.js for Testing

To use Jest with Node.js, first install Jest using npm install --save-dev jest. Then, write test files with .test.js extension and run tests using the jest command in your terminal.
📐

Syntax

Jest uses simple functions to define tests and expectations:

  • test(description, callback): Defines a test with a description and a function containing test code.
  • expect(value): Creates an expectation object for assertions.
  • toBe(expected): Checks if the value matches the expected value exactly.

This pattern helps you write clear and readable tests.

javascript
test('adds 1 + 2 to equal 3', () => {
  expect(1 + 2).toBe(3);
});
💻

Example

This example shows how to test a simple function that adds two numbers using Jest in Node.js.

javascript
// sum.js
function sum(a, b) {
  return a + b;
}
module.exports = sum;

// sum.test.js
const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});
Output
PASS ./sum.test.js ✓ adds 1 + 2 to equal 3 (5 ms) Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 1.234 s
⚠️

Common Pitfalls

Common mistakes when using Jest with Node.js include:

  • Not installing Jest as a dev dependency with npm install --save-dev jest.
  • Forgetting to add a test script in package.json like "test": "jest".
  • Using import syntax without configuring Node.js for ES modules (use require by default).
  • Writing test files without the .test.js or .spec.js suffix, so Jest does not find them.

Example of wrong and right test script in package.json:

json
{
  "scripts": {
    "test": "jest"
  }
}
📊

Quick Reference

CommandDescription
npm install --save-dev jestInstalls Jest as a development dependency
jestRuns all test files with .test.js or .spec.js suffix
test(description, callback)Defines a test case
expect(value).toBe(expected)Checks if value equals expected
npm testRuns the test script defined in package.json

Key Takeaways

Install Jest with npm as a dev dependency before writing tests.
Write test files ending with .test.js or .spec.js for Jest to detect them.
Use test() and expect() functions to define and check your tests.
Add a test script in package.json to run tests easily with npm test.
Avoid ES module syntax unless Node.js is configured for it; use require() by default.