Node.js Course
Node.js
/
Beginner

Jest

Definition

A delightful JavaScript Testing Framework maintained by Meta (Facebook) with a focus on simplicity. It provides assertions, mocking, and code coverage out of the box.

Explain Like I'm New

Writing code to test your code. Instead of manually clicking through your app every time you make a change to make sure you didn't break anything, you write a Jest script. You run `npm test`, and Jest executes your functions, automatically verifying that `add(2, 2)` still equals 4.

Real World Example

Running Jest tests automatically via GitHub Actions (CI/CD) every time a developer opens a Pull Request. If the tests fail, the PR is blocked from merging to prevent shipping bugs to production.

Common Use Cases

  • •Unit testing
  • •Test-Driven Development (TDD)
  • •Preventing regressions

Interactive Example

// --- file: math.js ---
const add = (a, b) => a + b;

// --- file: math.test.js ---
// Jest provides 'test' and 'expect' globally. No need to import them!

/*
test('adds 1 + 2 to equal 3', () => {
  // 1. Arrange (Setup the data)
  const a = 1;
  const b = 2;
  
  // 2. Act (Execute the function)
  const result = add(a, b);
  
  // 3. Assert (Verify the expectation)
  expect(result).toBe(3);
});
*/

console.log("Jest tests act as living documentation for how your functions are supposed to behave.");

Interview Questions

basic

  • What command is commonly used to execute Jest tests?

intermediate

  • What is an assertion?

Flash Cards

Question

What command?

Click to reveal answer
Answer

`npm test` (Which is mapped to the `jest` command in package.json).

Question

What is an assertion?

Click to reveal answer
Answer

A statement verifying that a condition is true. In Jest, it is written using the `expect()` function. E.g., `expect(result).toBe(4)`. If the result is not 4, the assertion throws an error and the test fails.