App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Get Started free
Home Guide How to Debug Jest Tests?

How to Debug Jest Tests?

By Arjun M. Shrivastva, Community Contributor -

Debugging Jest test scripts involves using the built-in debugging features and leveraging external tools to inspect and troubleshoot issues in your test code. In this article, we will provide a brief overview of debugging in Jest with ease.

Jest and its Role in JavaScript Testing

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

  • Jest plays a vital role in JavaScript testing by providing a robust and feature-rich framework that simplifies the process of writing tests.
  • It encourages test-driven development to ensure the reliability and quality of JavaScript applications, particularly those built with React.

Here’s an overview of Jest and its role in JavaScript testing:

  1. Comprehensive Testing: Jest provides comprehensive features for testing JavaScript code, including unit tests, integration tests, and end-to-end tests
  2. Inbuilt assertion Functions: Jest provides its own assertion functions and error reporting mechanisms that allow you to write tests and handle failures effectively. Some commonly used Jest functions include expect, describe, test, and various matchers like toBe, toEqual, and toThrow.
  3. Simplicity and Ease of Use: Comes pre-configured with sensible defaults. allowing you to start writing tests without spending time on complex setup or configuration.
  4. Snapshot Testing: One of its notable features is Jest snapshot testing which allows you to capture the rendered output of a component or the JSON representation of an object and store it as a reference 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 execution time through intelligent test parallelization, resulting in faster overall test execution.
  7. Code Coverage Analysis: It generates detailed reports that show which parts of your code are covered by tests and identifies areas that lack coverage.
  8. Integration with React: Seamlessly integrates with React and provides additional utilities for testing React components like shallow rendering.

Understanding Common Issues in Jest Testing

When working with Jest testing, developers may encounter several 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 behavior in the code being tested, or issues with the test setup. In a test failure analysis, It’s important to carefully review the failing test, check for errors or exceptions in the code, and verify that the test expectations are correctly defined.
  • Mocking Dependencies: When writing unit tests, it’s common to mock dependencies, but setting up mocks correctly can be challenging., especially when dealing with complex dependencies or asynchronous code. 
  • Asynchronous Testing: Asynchronous testing can be tricky, as Jest requires special handling for promises, async/await functions, and timers. Use the appropriate Jest functions like async/await, done, and waitFor to handle asynchronous code properly.
  • Configuration Issues: Jest has various configuration options, such as test environment setup, test file patterns, code coverage settings, and more. Double-check your Jest configuration, including the jest.config.js file, to ensure it aligns with your project’s requirements.

How to debug Jest Tests?

Prerequisites:

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

1. Configuring Jest for Debugging with BrowserStack

Integrating Jest with BrowserStack’s Selenium Grid allows you to run Jest tests on multiple browsers and platforms on a cloud infrastructure.

To integrate Jest with BrowserStack, follow these general steps:

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

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

Run the following commands in your project’s root directory:

npm init -y

npm install --save-dev jest

3. Jest requires a WebDriver implementation to communicate with the Selenium Grid. Install the Selenium WebDriver package as a dev dependency using npm.

npm install --save-dev selenium-webdriver

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

You’ll need the browserstack-node-sdk, which can be installed using the below command:

npm i -D browserstack-node-sdk@latest

5. Use the following command to create a browserstack.yml file in the root directory of your project and configure your access credentials:

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

The auto-generated browserstack.yml file in the root folder of your project contains all of the settings required to run tests on BrowserStack.

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

Like, We are running our script on the below configs:

platforms:

  - 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 following capabilities to take advantage of BrowserStack’s broad reporting features:

projectName: BrowserStack Tutorial

buildName: bstack demo

buildIdentifier: '#${BUILD_NUMBER}

3. Enable Debugging features
BrowserStack includes prettified session logs, screenshots of every unsuccessful Selenium command, and a video of the full test by default.

You can enable the following features:

debug: true # Set to true if you need screenshots for every selenium command ran

networkLogs: true # Set to true to enable HAR logs capturing

consoleLogs: info # Remote browser's console debug levels to be printed

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

We are demonstrating Sign In process on BrowserStack Demo Website in two examples. 

  • The first Jest debugging example one will cover the execution Locally
  • In the Second Jest debugging example we will automate the same flow to run that on BrowserStack.

2. Running Jest Tests Locally

For running your test script locally. You must download and add the desired driver to the project root directory. You can quickly get that from the official websites Chrome, Firefox, Safari, and Microsoft Edge. We are using Chrome WebDriver for this example.

First, add a new js file in <name>.test.js format (eg. local.test.js). And will write our test script as per our test case.

const { Builder, By, Key, until } = require('selenium-webdriver');

test('Sign In Test', async () => {

    // Set up Selenium WebDriver

    const driver = new Builder().forBrowser('chrome').build();

    try {

      // Navigate to a webpage

      await driver.get('https://bstackdemo.com/');

      // Find the sign-in button 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 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();

    } finally {

      // Close the browser

      await driver.quit();

    }

  });

To run that test script we have to modify the scripts part in package.json file as per that snippet:

"scripts": {

    "local-test": "jest filename"

  }

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

npm run local-test

You will see the result in the terminal.

Debug Jest Test Locally

3. Connecting Jest to BrowserStack for Remote Debugging

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

Let’s create another test file remote.test.js and understand the code changes step by step.

const { Builder, By, Key, until, Capabilities } = require("selenium-webdriver");

describe("BStack demo", () => {

  let driver;

  beforeAll(() => {

    driver = new Builder()

      .usingServer(`http://localhost:4444/wd/hub`)

      .withCapabilities(Capabilities.chrome())

      .build();

  });

 

  test('Sign In Test', async () => {

 

    try {

      // Navigate to a webpage

      await driver.get('https://bstackdemo.com/');

      // Find the sign-in button 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 name from the dropdown

      await driver.findElement(By.css('#react-select-2-option-0-0')).click();

      //Click on Password and select password 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

      await driver.findElement(By.id('login-btn')).click();

      //Wait for the logout button and assert 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, we have to 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 test case, use the below command and your test case will execute on BrowserStack:

npm run remote-test

You can see the result on BrowserStack Dashboard:

Jest debugging on BrowserStack

  • We are executing the same test case on two different configurations. Once the test execution is complete, you can view the test results in your BrowserStack Automate dashboard. It provides detailed information about the test runs, including logs, screenshots, and video recordings. 
  • As you can see in the above example, we did almost zero code changes to run the script on Remote.
  • Also, Broswerstack SDK enabled easy configuration on real devices and browsers, parallelization, and execution on localhost.

How to Debug Jest Tests?

4. Inspecting Test Execution in Real Browsers and Devices

BrowserStack allows you to run your Jest test suite on real browsers and devices, providing detailed logs, screenshots, and video recordings. These resources are invaluable for debugging and identifying the cause of any failures or inconsistencies.

By leveraging BrowserStack’s extensive browser matrix and device matrix, you can test your Jest tests across various platforms, including popular browsers, operating systems, and mobile devices.

Leveraging BrowserStack Test Observability

As part of BrowserStack’s ever-expanding infrastructure, Test Observability replaces all test reporting & debugging tools:

  • Instantly pinpoint failure reason with ML-based categorizations like product, automation, or environment issues
  • Access every log – framework, video, screenshot, terminal, network & even application logs – chronologically sorted in a single pane. 
  • Troubleshoot test suite health with built-in dashboards for metrics like stability and flakiness.

Use BrowserStack Test Observability

Tags
Automation Testing Unit Testing

Featured Articles

Jest Framework Tutorial: How to use it?

Unit Testing of React Apps using JEST : Tutorial

App & Browser Testing Made Easy

Seamlessly test across 20,000+ real devices with BrowserStack