Convert Figma logo to code with AI

jestjs logojest

Delightful JavaScript Testing.

44,045
6,430
44,045
349

Top Related Projects

44,043

Delightful JavaScript Testing.

22,534

☕️ simple, flexible, fun javascript test framework for node.js & the browser

15,728

Simple JavaScript testing framework for browsers and node.js

46,661

Fast, easy and reliable testing for anything that runs in a browser.

20,716

Node.js test runner that lets you develop with confidence 🚀

12,615

Next generation testing framework powered by Vite.

Quick Overview

Jest is a popular JavaScript testing framework developed by Facebook. It provides a complete and easy-to-set-up testing solution for JavaScript projects, with a focus on simplicity and minimal configuration. Jest is widely used for testing React applications but can be used for any JavaScript project.

Pros

  • Zero configuration required for most JavaScript projects
  • Built-in code coverage reports
  • Fast parallel test execution
  • Powerful mocking capabilities

Cons

  • Can be slower for large test suites compared to some alternatives
  • Learning curve for advanced features and configurations
  • Some users report occasional inconsistencies in test results

Code Examples

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

This example demonstrates a simple Jest test that checks if 1 + 2 equals 3.

  1. Asynchronous test example:
test('fetches user data', async () => {
  const data = await fetchUserData(1);
  expect(data.name).toBe('John Doe');
});

This example shows how to test asynchronous code using async/await syntax.

  1. Mocking example:
jest.mock('./api');
import { fetchUserData } from './api';

test('mocks API call', () => {
  fetchUserData.mockResolvedValue({ id: 1, name: 'John Doe' });
  
  return fetchUserData(1).then(data => {
    expect(data.name).toBe('John Doe');
  });
});

This example demonstrates how to mock an API call using Jest's mocking capabilities.

Getting Started

To get started with Jest, follow these steps:

  1. Install Jest in your project:
npm install --save-dev jest
  1. Add a test script to your package.json:
{
  "scripts": {
    "test": "jest"
  }
}
  1. Create a test file (e.g., sum.test.js):
const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});
  1. Run your tests:
npm test

Jest will automatically find and run your tests, providing detailed output and results.

Competitor Comparisons

44,043

Delightful JavaScript Testing.

Pros of Jest

  • Widely adopted and well-maintained testing framework
  • Extensive documentation and community support
  • Built-in code coverage reporting

Cons of Jest

  • Can be slower for large test suites
  • Configuration can be complex for advanced use cases
  • Some users report occasional inconsistencies in test results

Code Comparison

Jest:

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

Jest:

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

Summary

Jest is a popular JavaScript testing framework known for its simplicity and powerful features. It offers a comprehensive solution for unit testing, integration testing, and snapshot testing. The framework provides a rich set of matchers, mocking capabilities, and built-in code coverage reporting.

Both repositories (jestjs/jest and jestjs/jest) refer to the same project, so there are no significant differences to compare. Jest continues to be actively developed and maintained by the open-source community, with regular updates and improvements.

When choosing Jest for your project, consider factors such as your team's familiarity with the framework, the size of your test suite, and your specific testing requirements. While Jest excels in many areas, it may not be the best fit for every project, especially those with very large test suites or unique testing needs.

22,534

☕️ simple, flexible, fun javascript test framework for node.js & the browser

Pros of Mocha

  • More flexible and customizable testing framework
  • Supports a wider range of assertion libraries and reporters
  • Better suited for complex, asynchronous testing scenarios

Cons of Mocha

  • Requires more setup and configuration
  • Slower test execution compared to Jest
  • Lacks built-in mocking and code coverage tools

Code Comparison

Mocha:

describe('Array', function() {
  describe('#indexOf()', function() {
    it('should return -1 when the value is not present', function() {
      assert.equal([1, 2, 3].indexOf(4), -1);
    });
  });
});

Jest:

describe('Array', () => {
  describe('#indexOf()', () => {
    it('should return -1 when the value is not present', () => {
      expect([1, 2, 3].indexOf(4)).toBe(-1);
    });
  });
});

Both Jest and Mocha are popular JavaScript testing frameworks, each with its own strengths and weaknesses. Mocha offers more flexibility and customization options, making it suitable for complex testing scenarios. However, it requires more setup and configuration compared to Jest. Jest, on the other hand, provides a more streamlined experience with built-in mocking and code coverage tools, but may be less flexible for certain use cases. The choice between the two often depends on the specific needs of the project and the development team's preferences.

15,728

Simple JavaScript testing framework for browsers and node.js

Pros of Jasmine

  • Simpler setup and configuration out of the box
  • Lightweight and faster for smaller projects
  • Better support for testing asynchronous code with built-in async matchers

Cons of Jasmine

  • Less comprehensive mocking capabilities
  • Lacks built-in code coverage reporting
  • Smaller ecosystem and fewer plugins compared to Jest

Code Comparison

Jasmine:

describe('Calculator', () => {
  it('should add two numbers', () => {
    expect(add(2, 3)).toBe(5);
  });
});

Jest:

test('adds two numbers', () => {
  expect(add(2, 3)).toBe(5);
});

Both Jest and Jasmine are popular JavaScript testing frameworks, but they have different strengths and use cases. Jasmine is simpler to set up and use, making it a good choice for smaller projects or those new to testing. It also has better built-in support for asynchronous testing.

Jest, on the other hand, offers more comprehensive features, including powerful mocking capabilities and built-in code coverage reporting. It also has a larger ecosystem with more plugins and integrations available.

In terms of syntax, both frameworks are quite similar, as shown in the code comparison. The main difference is that Jest uses the test function, while Jasmine uses it within a describe block. Both use expect for assertions.

Ultimately, the choice between Jest and Jasmine depends on the specific needs of your project and team preferences.

46,661

Fast, easy and reliable testing for anything that runs in a browser.

Pros of Cypress

  • Real-time browser testing with automatic waiting
  • Built-in time travel and debugging tools
  • Easier setup and configuration for end-to-end testing

Cons of Cypress

  • Limited to JavaScript for test writing
  • Primarily focused on front-end testing
  • Slower test execution compared to Jest

Code Comparison

Jest:

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

Cypress:

it('adds 1 + 2 to equal 3', () => {
  cy.visit('/calculator');
  cy.get('#num1').type('1');
  cy.get('#num2').type('2');
  cy.get('#add').click();
  cy.get('#result').should('have.text', '3');
});

Jest is a JavaScript testing framework primarily used for unit and integration testing, while Cypress is an end-to-end testing tool focused on web applications. Jest offers a simple and fast testing experience with a rich set of matchers and mocking capabilities. It's well-suited for testing React applications and provides good performance for large test suites.

Cypress, on the other hand, excels in creating and running end-to-end tests in a real browser environment. It provides a more user-friendly interface for test creation and debugging, making it easier for developers to write and maintain complex UI tests. However, Cypress is more specialized and may not be as versatile for different types of testing compared to Jest.

20,716

Node.js test runner that lets you develop with confidence 🚀

Pros of AVA

  • Faster test execution due to concurrent running of tests
  • Minimal and clean syntax, leading to more readable test code
  • Built-in support for ES6 and async functions without additional configuration

Cons of AVA

  • Smaller ecosystem and fewer plugins compared to Jest
  • Less out-of-the-box functionality, requiring more setup for certain features
  • Steeper learning curve for developers accustomed to more traditional testing frameworks

Code Comparison

AVA:

import test from 'ava';

test('foo', t => {
    t.pass();
});

test('bar', async t => {
    const bar = Promise.resolve('bar');
    t.is(await bar, 'bar');
});

Jest:

describe('foo', () => {
    it('should pass', () => {
        expect(true).toBe(true);
    });

    it('should resolve to bar', async () => {
        const bar = Promise.resolve('bar');
        await expect(bar).resolves.toBe('bar');
    });
});

Both AVA and Jest are popular JavaScript testing frameworks, each with its own strengths. AVA focuses on simplicity and speed, while Jest offers a more comprehensive feature set out of the box. The choice between them often depends on project requirements and team preferences.

12,615

Next generation testing framework powered by Vite.

Pros of Vitest

  • Faster execution due to Vite-based architecture
  • Native TypeScript support without additional configuration
  • Simpler setup and configuration process

Cons of Vitest

  • Smaller ecosystem and community compared to Jest
  • Less mature and potentially less stable for large-scale projects
  • Limited compatibility with some Jest plugins and extensions

Code Comparison

Jest:

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

Vitest:

import { expect, test } from 'vitest'

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

Key Differences

  • Vitest leverages Vite's fast bundling and hot module replacement
  • Jest has a larger set of built-in matchers and utilities
  • Vitest aims for better performance in modern JavaScript projects
  • Jest offers more extensive documentation and community resources

Use Cases

  • Choose Vitest for projects already using Vite or seeking faster test execution
  • Opt for Jest in larger projects requiring extensive ecosystem support
  • Consider Vitest for TypeScript-heavy projects to avoid additional setup

Community and Adoption

  • Jest has a larger user base and more widespread adoption
  • Vitest is gaining popularity, especially in the Vue.js ecosystem
  • Both projects are actively maintained and regularly updated

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

npm version Jest is released under the MIT license. Follow on Twitter

GitHub CI Status Coverage Status

Gitpod ready-to-code

 

🃏 Delightful JavaScript Testing

👩🏻‍💻 Developer Ready: A comprehensive JavaScript testing solution. Works out of the box for most JavaScript projects.

🏃🏽 Instant Feedback: Fast, interactive watch mode only runs test files related to changed files.

📸 Snapshot Testing: Capture snapshots of large objects to simplify testing and to analyze how they change over time.

See more on jestjs.io

Table of Contents

Getting Started

Install Jest using yarn:

yarn add --dev jest

Or npm:

npm install --save-dev jest

Note: Jest documentation uses yarn commands, but npm will also work. You can compare yarn and npm commands in the yarn docs, here.

Let's get started by writing a test for a hypothetical function that adds two numbers. First, create a sum.js file:

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

Then, create a file named sum.test.js. This will contain our actual test:

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

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

Add the following section to your package.json:

{
  "scripts": {
    "test": "jest"
  }
}

Finally, run yarn test or npm test and Jest will print this message:

PASS  ./sum.test.js
✓ adds 1 + 2 to equal 3 (5ms)

You just successfully wrote your first test using Jest!

This test used expect and toBe to test that two values were exactly identical. To learn about the other things that Jest can test, see Using Matchers.

Running from command line

You can run Jest directly from the CLI (if it's globally available in your PATH, e.g. by yarn global add jest or npm install jest --global) with a variety of useful options.

Here's how to run Jest on files matching my-test, using config.json as a configuration file and display a native OS notification after the run:

jest my-test --notify --config=config.json

If you'd like to learn more about running jest through the command line, take a look at the Jest CLI Options page.

Additional Configuration

Generate a basic configuration file

Based on your project, Jest will ask you a few questions and will create a basic configuration file with a short description for each option:

yarn create jest

Using Babel

To use Babel, install required dependencies via yarn:

yarn add --dev babel-jest @babel/core @babel/preset-env

Configure Babel to target your current version of Node by creating a babel.config.js file in the root of your project:

// babel.config.js
module.exports = {
  presets: [['@babel/preset-env', {targets: {node: 'current'}}]],
};

The ideal configuration for Babel will depend on your project. See Babel's docs for more details.

Making your Babel config jest-aware

Jest will set process.env.NODE_ENV to 'test' if it's not set to something else. You can use that in your configuration to conditionally setup only the compilation needed for Jest, e.g.

// babel.config.js
module.exports = api => {
  const isTest = api.env('test');
  // You can use isTest to determine what presets and plugins to use.

  return {
    // ...
  };
};

Note: babel-jest is automatically installed when installing Jest and will automatically transform files if a babel configuration exists in your project. To avoid this behavior, you can explicitly reset the transform configuration option:

// jest.config.js
module.exports = {
  transform: {},
};

Using webpack

Jest can be used in projects that use webpack to manage assets, styles, and compilation. webpack does offer some unique challenges over other tools. Refer to the webpack guide to get started.

Using Vite

Jest can be used in projects that use vite to serves source code over native ESM to provide some frontend tooling, vite is an opinionated tool and does offer some out-of-the box workflows. Jest is not fully supported by vite due to how the plugin system from vite works, but there is some working examples for first-class jest integration using the vite-jest, since this is not fully supported, you might as well read the limitation of the vite-jest. Refer to the vite guide to get started.

Using Parcel

Jest can be used in projects that use parcel-bundler to manage assets, styles, and compilation similar to webpack. Parcel requires zero configuration. Refer to the official docs to get started.

Using TypeScript

Jest supports TypeScript, via Babel. First, make sure you followed the instructions on using Babel above. Next, install the @babel/preset-typescript via yarn:

yarn add --dev @babel/preset-typescript

Then add @babel/preset-typescript to the list of presets in your babel.config.js.

// babel.config.js
module.exports = {
  presets: [
    ['@babel/preset-env', {targets: {node: 'current'}}],
+    '@babel/preset-typescript',
  ],
};

However, there are some caveats to using TypeScript with Babel. Because TypeScript support in Babel is purely transpilation, Jest will not type-check your tests as they are run. If you want that, you can use ts-jest instead, or just run the TypeScript compiler tsc separately (or as part of your build process).

Documentation

Learn more about using Jest on the official site!

Badge

Show the world you're using Jest → tested with jest jest tested jest

[![tested with jest](https://img.shields.io/badge/tested_with-jest-99424f.svg?logo=jest)](https://github.com/jestjs/jest)
[![jest tested](https://img.shields.io/badge/Jest-tested-eee.svg?logo=jest&labelColor=99424f)](https://github.com/jestjs/jest)
[![jest](https://jestjs.io/img/jest-badge.svg)](https://github.com/jestjs/jest)

Contributing

Development of Jest happens in the open on GitHub, and we are grateful to the community for contributing bugfixes and improvements. Read below to learn how you can take part in improving Jest.

Code of Conduct

Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please read the full text so that you can understand what actions will and will not be tolerated.

Contributing Guide

Read our contributing guide to learn about our development process, how to propose bugfixes and improvements, and how to build and test your changes to Jest.

Good First Issues

To help you get your feet wet and get you familiar with our contribution process, we have a list of good first issues that contain bugs which have a relatively limited scope. This is a great place to get started.

Credits

This project exists thanks to all the people who contribute.

Backers

Thank you to all our backers! 🙏

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website.

License

Jest is MIT licensed.

Copyright

Copyright Contributors to the Jest project.

NPM DownloadsLast 30 Days