DEV Community

Muchhal Sagar
Muchhal Sagar

Posted on

Mastering Jest: A Guide to Efficient JavaScript Testing

Jest is a popular javascript testing framework (also known as jest is open sourch testing framework) designed to ensure correctness of any codebase. it allows you to write test with an approchable familiar and featured-rich API that gives you result quickly. jest is well-documented, reqiuires lottle configuration and can be extended to match your requirments.

Key Features of Jest:

zero configuration: jest work out of the box with minimal setup.
Fast and effecient: parralel test execution speeds up tetsing process.
Snapshot testing: compare and capture UI Snapshot.
Built-in Mocks and spies: Simplyfies mocking dependencies.
Code Coverage: generate detailed code reports.
Extenshive community Supports: a large ecosystem of plugins and tools.

Installing Jest
you can install jest in your project using nom or yarn.

# using npm
npm install --save-dev jest

$ using yarn
yarn add -dev jest
Enter fullscreen mode Exit fullscreen mode

For typescript Projects, also install the types:

npm install --save-dev @types/jest
Enter fullscreen mode Exit fullscreen mode

Writing Your first Test
create a new file, sum.test.js, in your projrct

// 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);
});
Enter fullscreen mode Exit fullscreen mode

Run the test using:

npx jest
Enter fullscreen mode Exit fullscreen mode

If everything is set up correctly, Jest will output:

PASS  ./sum.test.js
  ✓ adds 1 + 2 to equal 3
Enter fullscreen mode Exit fullscreen mode

Top comments (0)