How to Debug Jest Tests?

On This Page What is Jest?Role of Jest in JavaScript TestingMay 21, 2026 · 12 min read · Testing Guide

How to Debug Jest Tests?

Jestis a powerful JavaScript testing framework designed to streamline application testing. It integrates seamlessly with most task and offers advanced features like mocking, code coverage, and snapshot examination.

Debugging Jest testsis crucial for identifying and repair number and ensuring your code purpose as expected.

This guidebook extend effective debugging proficiency to improve Jest test accuracy and efficiency.

What is Jest?

is a popular Meta (formerly Facebook Open Source) developed. It is well-suited for test React applications—Babel, TypeScript, Node, Angular, Vue, etc.

  • Jest plays a vital role in JavaScript testing by providing a robust and feature-rich fabric that simplifies the process of indite tests.
  • It encourages to ensure the reliability and lineament of JavaScript applications, particularly those built with React.

Must Read:

Role of Jest in JavaScript Testing

Here & # 8217; s an overview of Jest and its part in JavaScript testing:

  1. Comprehensive Testing:Jest provides comprehensive feature for test JavaScript codification, include,, and.
  2. Inbuilt assertion Functions:Jest provides its own assertion functions and error reporting mechanics that allow you to write tryout and handle failures effectively. Some commonly used Jest functions includeexpect, describe, test, and various matchers like toBe, toEqual, and toThrow.
  3. Simplicity and Ease of Use:Comes pre-configured with sensitive defaults. allowing you to commence writing examination without spending time on complex frame-up or constellation.
  4. Snapshot Testing:One of its notable features is which allows you to trance the rendered output of a component or the JSON representation of an object and store it as a cite snapshot.
  5. Mocking and Spies:Provides powerful mocking capabilities that allow you to isolate your tests and simulate different scenarios.
  6. Fast and Parallel Test Execution:Optimizes test performance time through intelligent test parallelization, lead in faster overall trial execution.
  7. Code Coverage Analysis:It yield detailed reports that show which part of your code are covered by tests and identifies country that lack coverage.
  8. Integration with React:Seamlessly integrates with React and supply additional utilities for like shallow interpreting.

Understanding Common Issues in Jest Testing

When act with Jest testing, developer may encounter various common issues. These issues can occur when writing test cases, configuring Jest, or running tests.

  • Test Failures:Test failures can occur due to incorrect assertions, unexpected demeanour in the code being tested, or issues with the test setup. In a, It & # 8217; s significant to cautiously review the failing test, check for error or exception in the codification, and verify that the test prospect are correctly defined.
  • Mocking Dependencies:When writing unit exam, it & # 8217; s common to bemock dependencies, but setting up mock correctly can be challenging., especially when consider with complex dependencies or asynchronous code.
  • Asynchronous Testing:Asynchronous prove can be tricky, as Jest requires exceptional handling for promises, async/await function, and timers. Use the appropriate Jest functions like async/await, done, and waitFor to plow asynchronous code properly.
  • Configuration Issues:Jest has various conformation options, such as test environs setup, test file patterns, codification coverage settings, and more. Double-check your Jest configuration, including the jest.config.js file, to ensure it aligns with your project & # 8217; s requirements.

How to Debug Jest Tests?

Debugging is the process of finding and purpose errors in your tests. Jest offers multiple methods to help debug your codification efficaciously:

1. Use console.log ():Add console.log () to your code to print values and check the flowing of performance.

2. Insert a debugger Statement:Place debugger in your codification, then run Jest in debug way to pause execution and inspect variables.

3 .Debug with VSCode:Use Visual Studio Code ’ s debug creature to pause and scrutinise code with breakpoints.

Read More:

4. Debug with IntelliJ IDEA:IntelliJ supply an easy-to-use debugger to inspect codification while running Jest tests.

5. Use Jest Flags: Run Jest with helpful fleur-de-lis like:

  • inspectto attach a debugger.
  • watchto mechanically re-run tests when changes are made.

6. Third-party Tools: Cloud platform like BrowserStack grant you to debug Jest tests across real browsers and device, simplify cross-browser testing.

How to Debug Jest Tests with VSCode?

Debugging Jest trial in VSCode involves setting up a debug configuration to run your test instance now from the IDE.

Step 1: Set up Jest in your project

  • Ensure Jest is establish and configure in your task.
  • If not, run the following bid:
npm install -- save-dev jest

Step 2: Add a Debug Configuration

  • Open the Run and Debug view (Ctrl+Shift+D).
  • Click on create alaunch.json file.
  • Select Node.jsand replace the form with:
{'' type '': `` node '', '' request '': `` launch '', '' name '': `` Debug Jest Tests '', '' program '': `` $ {workspaceFolder} /node_modules/jest/bin/jest.js '', '' args '': [`` -- runInBand ''], '' console '': `` integratedTerminal '',}

Step 3: Set Breakpoints

Open your test file and click on the line figure where you require the execution to break.

Step 4: Run the Debugger

Select the & # 8220; Debug Jest Tests & # 8221; configuration.
Click the drama button or press F5 to commence debugging.

Read More:

How to Debug Jest Tests in IntelliJ?

IntelliJ IDEA allows seamless debugging of Jest test with its integrate.

Step 1: Set up Jest in your project

Install Jest vianpm or yarnand configure it in yourpackage.json file.

Step 2: Create a Jest Configuration

  • Go to Run & gt; Edit Configurations.
  • Click + and selectJest.
  • Specify the Jest binary path and working directory.

Step 3: Set Breakpoints

Open your test file and detent next to the line numbers to set breakpoints.

Step 4: Run Debug

  • Select the Jest shape from the dropdown menu.
  • Click the debug image to start debugging. The debugger will cease at breakpoints for review.

How to debug Jest Tests Using BrowserStack?

To debug Jest tests effectively on BrowserStack below are some pre-requisites followed by a step-by-step guide on how to action and debug Jest exam on the.

Prerequisites:

  • You must have a BrowserStack Username and Access Key, which can be found in your history profile. If you still want to do so, you can.
  • Node v12+ is installed on your machine.
  • Any IDE to write and edit your JavaScript codification (eg.VS Code, Atom, IntelliJ, etc.)

1. Configuring Jest for Debugging with BrowserStack

Integrating allows you to run Jest tests on multiple browsers and platforms on a cloud infrastructure.

For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.

To desegregate Jest with BrowserStack, follow these general steps:

1.Create a new folder and open it using your IDE.

2.Set up Jest in your undertaking by initializing a new npm bundle and installing Jest as a dev dependency.

Run the following command in your project & # 8217; s root directory:

npm init -y



npm install -- save-dev jest

3.Jest requires a WebDriver execution to pass with the Selenium Grid. Install the package as a dev addiction utilise npm.

npm install -- save-dev selenium-webdriver

4.Install the necessary dependencies for pass Jest tests with BrowserStack.

You & # 8217; ll demand the browserstack-node-sdk, which can be installed expend the below command:

npm i -D browserstack-node-sdk @ latest

5.Use the next bidding to create a browserstack.yml file in the root directory of your project and configure your access credential:

npx setup -- username your-username -- key your-key

The auto-generated browserstack.yml file in the root folder of your task control all of the background involve to run test on BrowserStack.

1. Set platforms to test on
Set the browsers and device you desire to test under the platforms object. Our config follows W3C formatted capabilities.

Run the hand on the below configs:

program: - os: OS X osVersion: Big Sur browserName: Chrome browserVersion: latest - os: Windows osVersion: 10 browserName: Edge browserVersion: latest

2. BrowserStack Reporting

You can use the next capabilities to take reward of BrowserStack & # 8217; s blanket reporting features:

projectName: BrowserStack Tutorial buildName: bstack demo buildIdentifier: ' # $ {BUILD_NUMBER}

3. Enable Debugging features

BrowserStack includes prettified session logs, screenshots of every abortive Selenium bid, and a picture of the full test by default.

You can enable the next features:

debug: true # Set to true if you need screenshots for every selenium bid ran networkLogs: true # Set to true to enable HAR logs capturing consoleLogs: info # Remote browser 's console debug levels to be publish

Now your model is ready. You can create a new JavaScript file and add a hand as per your requirement.

The sign-in process will be demonstrated onBrowserStack Demo Websitein two model.

  • The initiative Jest debugging example one will extend the execution Locally
  • In the Second Jest debugging example automate the like flow to run it on BrowserStack.

2. Running Jest Tests Locally

For running your test script topically. You must download and add the craved driver to the project root directory. You can quickly get that from the official websitesChrome, Firefox, Safari, and Microsoft Edge. Chrome WebDriver is used for this example.

First, add a new js file in& lt; name & gt; .test.jsformatting (eg.local.test.js). And will publish our examination book as per our test case.

const{Builder, By, Key, until} = require ('selenium-webdriver '); examination ('Sign In Test ', async ()=>{// Set up Selenium WebDriverconstdriver = new Builder () .forBrowser ('chrome ') .build (); try {// Navigate to a webpage await driver.get ('https: //bstackdemo.com/ '); // Find the sign-in push and dog on it await driver.findElement (By.css (`` # signin '')) .click (); //Wait for Username visibility and then snap on it await driver.wait (until.elementLocated (By.id (`` username ''))) .click (); //Select User name from dropdown await driver.findElement (By.css (' # react-select-2-option-0-0 ')) .click (); //Click on Password and select password from the Dropdown await driver.findElement (By.id ('password ')) .click (); await driver.findElement (By.css (' # react-select-3-option-0-0 ')) .click (); //Click on Log In Button await driver.findElement (By.id ('login-btn ')) .click (); //Wait for logout button and assert its visibility await driver.wait (until.elementLocated (By.css (`` # logout ''))) .isDisplayed ();} ultimately {// Close the browser await driver.quit ();}});

To run that trial hand modify the scripts component in package.json file as per that snippet:

"scripts": {



    `` local-test '': `` jest filename ''}

By using the below command our test case will be accomplish:

npm run local-test

You will see the result in the depot.

3. Connecting Jest to BrowserStack for Remote Debugging

The test playscript above executes on a local browser to execute the same test remotely on BrowserStack.

Let & # 8217; s create another test file remote.test.js and understand the code change step by step.

const{Builder, By, Key, until, Capabilities} = require (`` selenium-webdriver ''); describe (`` BStack demonstration '', ()=> {



  letdriver; beforeAll (()=>{driver = new Builder () .usingServer (` http: //localhost:4444/wd/hub `) .withCapabilities (Capabilities.chrome ()) .build ();}); tryout ('Sign In Test ', async ()=>{try {// Navigate to a webpage await driver.get ('https: //bstackdemo.com/ '); // Find the sign-in push and click on it await driver.findElement (By.css (`` # signin '')) .click (); //Wait for Username visibility and then click on it await driver.wait (until.elementLocated (By.id (`` username ''))) .click (); //Select User gens from the dropdown await driver.findElement (By.css (' # react-select-2-option-0-0 ')) .click (); //Click on Password and select word from Dropdown await driver.findElement (By.id ('password ')) .click (); await driver.findElement (By.css (' # react-select-3-option-0-0 ')) .click (); //Click on Log In Button wait driver.findElement (By.id ('login-btn ')) .click (); //Wait for the logout button and verify its visibility await driver.wait (until.elementLocated (By.css (`` # logout ''))) .isDisplayed ();} finally {// Close the browser await driver.quit ();} //Changing the default timeout of 5000 to 10000 MS}, 120000);});

To add the script to run the remote-test, update the package.json file as shown below:

"scripts": {



    `` remote-test '': `` browserstack-node-sdk jest filename '',`` postinstall '': `` npm update browserstack-node-sdk '',`` local-test '': `` jest local.test.js ''},

To run that exam case, use the below dictation and your test case will execute on BrowserStack:

npm run remote-test

You can see the result on BrowserStack Dashboard:

  • Here, the same test case is executed on two different constellation. Once the exam execution is complete, you can view the tryout results in your fascia. It provides elaborate info about the test runs, including logs, screenshots, and picture transcription.
  • As you can see in the above model, well-nigh zero code changes be execute to run the script on Remote.
  • Also, enabled easy constellation on real devices and browsers, parallelization, and execution on localhost.

4. Inspecting Test Execution in Real Browsers and Devices

BrowserStack allows you to run your Jest test suite on real browser and devices, providing elaborate logs, screenshots, and video recording. These resources are invaluable for debug and name the reason of any failure or inconsistencies.

By leverage BrowserStack & # 8217; s extensive and, you can prove your Jest test across several platforms, including democratic browsers, operating scheme, and mobile devices.

How to Run Failed Test Cases in Jest

Jest can rerun just the failed test cases using the& # 8211; onlyFailures flag.

Step 1: Run All Tests

Run your trial suite utilize the undermentioned command:
jest

Or, if you ’ re employ npm:
npm test.

Step 2: Identify Failed Tests

Jest mechanically tracks failed exam in its hoard.

Step 3: Rerun Failed Tests

Use the following command to rerun only failed tests:

jest -- onlyFailures

Note: This command will automatically regain and rerun merely those tests that failed in the previous run.

Read More:

Debugging Jest Tests with BrowserStack Test Observability

enhances Jest test debugging by providing comprehensive insights and real-time reporting. It consolidates all debugging creature into a individual program, create subject detection and firmness faster and more efficient.

  • Identify Failures Instantly: ML-driven failure categorization helps pinpoint whether issues stem from the product, mechanization, or environs.
  • Comprehensive Log Access: View model logs, video recording, screenshots, terminal yield, network requests, and application logs—all in one place.
  • Analyze Health: Built-in fascia provide key prosody like test stability and flakiness, helping maintain reliable trial execution.

Useful Resources for Jest

Talk to an Expert

Conclusion

Debugging Jest tests efficiently requires a combination of tools, strategies and practices. Whether you are utilise console logarithm, debugger statement or IDE integrations like VSCode and IntelliJ, the goal is to gain clarity and fix number quickly.

Tools like BrowserStack can encourage raise your examination by providing cloud environments to debug Jest tests across multiple browsers and devices, ensuring.

Frequently Asked Questions

1. How do I run a test in debug way?

You can run Jest test in debug manner by expend like VSCode or IntelliJ or by running Jest with the& # 8211; inspectmasthead to attach a debugger.

2. How to prove for erroneousness in Jest?

Use Jest ’ s built-in toThrow()matcher to test error scenario.

For example:

examination ('throws an error ', () = & gt; {expect (() = & gt; someFunction ()) .toThrow ('Error content ');});

With these approach, you can easy debug and fix matter in your Jest test cases.

Tags
77,000+ Views

# Ask-and-Contributeabout this matter with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free