Run Jest Tests for Specific Files and Folders with Ease

Accelerate your test execution with BrowserStack Automate. Run your Jest tests on a real device cloud, ensuring flawless performance across all environments.

Get Started free
Home Guide How to Run Jest Tests for a Specific File/Folder

How to Run Jest Tests for a Specific File/Folder

By GH, Community Contributor -

Software Testing is an integral part of the Software Development Life Cycle, comprising different phases, such as Unit Testing, Component Testing, API Testing, Integration Testing, Functional Testing, UI Testing, and End-to-End Testing. Component testing helps validate the individual components or units of the system. 

Jest framework supports Component Testing, particularly for modern frameworks like React, VueJS, and Angular. Its ability to seamlessly test individual components in isolation, combined with its simplicity, customization, and extensibility, makes Jest an invaluable tool for developers. Additionally, as an open-source and free-to-use framework, Jest provides both power and accessibility, helping ensure robust software performance across various platforms.

This guide will show you how to run Jest tests for specific files or folders, helping you streamline your testing process and focus on what matters most.

Overview of Jest Testing Framework

Jest is a popular open-source NodeJS framework initially developed by Facebook. It can be used for component testing and end-to-end testing, and it can be integrated into popular test automation tools such as WebdriverIO, Playwright, etc. Jest has many advantages, some of which are listed below.

  • It requires minimal configuration to run the tests
  • It can be integrated with popular NodJS front-end frameworks such as VueJS, React, Angular, etc.
  • It also supports popular end-to-end testing frameworks like WebdriverIO, Playwright, etc.
  • Jest is an open-source framework and free to use
  • It provides many built-in capabilities, such as skipping, running specific, and running tests based on regular expression patterns.
  • A large set of matches to validate the test results
  • Supports Asynchronous Testing
  • Debugging capability, Mocking, and faster execution are a few key features of Jest.

Why Should You Run Jest Tests for a Specific File/Folder?

Jest supports running tests in specific files or folders. This helps in many scenarios, such as debugging, testing specific features, getting faster feedback, etc. 

Consider this example: If you are developing a feature related to search functionality, you may not be bothered about the checkout cart, login, etc. In such scenarios, you can only execute the tests specific to the search functionality. Jest provides an easy syntax for running specific tests. 

Step by Step Guide to Run Set up Jest and Run Specific File

Pre-requisite: 

Step 1: Configure Folders

Using the Folder Explorer, Create an empty directory (Example: JestDemo)

Step 2: Open the newly created directory in VSCode

Using Visual Studio Code, Click on File > Open Folder and Choose newly created directory (JestDemo)

Step 3: Install Jest

In VS Code, Click on Terminal and Choose New Terminal

From the New Terminal, Execute the below command

npm install jest

Step 4: Let’s create a sample component to test

Create a new file called stringoperation.js and copy and paste the below code

module.exports.getVowelsCount= function (string3) {

    let vowelsCount = 0;

  let Vowels = "aAeEiIoOuU";

    for (let i = 0; i < string3.length; i++) {

        if (Vowels.indexOf(string3[i]) !== -1) {

            vowelsCount += 1;

        }

    }

    return vowelsCount;

}

module.exports.stringConcat= function (string1,string2) {

   return string1+string2;

}

module.exports.extractNumbersFromString = function(string){

    return string.match(/\d+/)[0]

}

The above code performs 3 different string operations

  • getVowelsCount: returns the number of vowels in the given string
  • stringConcat: Concatenates two strings and returns the concatenated string
  • extractNumbersFromString: Returns the numbers in the given string

Step 4: Write a Jest test to validate the above operations

To understand different jest operations, create a Jest test in the folder structure below.

Create a folder called string-operations and write tests.

Create a new file extractnumber.test.js  under the string-operations folder and write a test to validate the extract number functionality as below

//extractnumber.test.js

const{extractNumbersFromString}= require('../stringoperations.js')

test('Verify Numbers in String', () => {

  var numbersInString = extractNumbersFromString("BrowserStack is No.1 tool")

  expect(numbersInString).toEqual("1");

})

Create a new file stringconcat.test.js under the string-operations folder and write a test to validate the string concat operation as below

//stringconcat.test.js

const{stringConcat}= require('../stringoperations.js')

test('Verify String Concatenation', () => {

  var concatString = stringConcat("BrowserStack", "Tool to test")

  expect(concatString).toEqual("BrowserStackTool to test");

})

Create a new folder called string-vowels-test and create a new file under the same folder vowels.test.js. Use the below test code

//vowels.test.js

const{getVowelsCount}= require('../stringoperations.js')

test('Verify Vowels in String', () => {

  var vowels = getVowelsCount("Browserstack is the popular testing tool");

  expect(vowels).toEqual(12);

})

After the creation of the above folders and test files, your project should look like this:

Jest execute

Different ways to execute Jest Tests 

This section helps you to understand how to run the above created tests. As mentioned earlier, Jest provides different ways to run the tests. You can run jest tests on a specific file(s), specific folder(s), or with a regular expression, and you can even skip specific tests.

Run Jest Test for a Specific File

In the above project, we have created different tests. Let’s execute only a test to get the number of vowels in a given string. The vowel count test resides in the vowels.test.js file. To execute a single jest test follow the below syntax.

npx jest <filename>

Example:

npx jest vowels.test.js

Output:

Output 1 passed

Run Jest tests for a Specific Folder

To run Jest tests for a specific folder, the syntax remains the same as running tests for a specific file; instead of the file, you must pass the folder name. In the above project, you have created a folder called string-operations, which has two files namely extractnumber.test.js and stringconcat.test.js. If you execute the string-operations folder, then both tests should be executed.

Syntax:

npx jest <folder_name>

Example:

npx jest string-operations

Output:

Output 2 passed

Running a Single Test Using ‘only’ or ‘f’

Jest supports executing single tests within the same file. To execute a single test in a Jest you can use the “only” postfix to your tests such as it.only(), test.only(), describe.only() etc. 

Read More: How to debug Jest.

In the above-created project, modify the file vowels.test.js file to the below code

const{getVowelsCount}= require('../stringoperations.js')

test('Verify Vowels in First String', () => {

  var vowels = getVowelsCount("Browserstack is the popular testing tool");

  expect(vowels).toEqual(12);

})

test('Verify Vowels in Second String', () => {

  var vowels = getVowelsCount("Browserstack is a tool");

  expect(vowels).toEqual(7);

})

In the above code, two tests were created – ‘Verify Vowels in First String‘ and ‘Verify Vowels in Second String’. If you want to execute only one of these tests, you can modify the code below.

//vowels.test.js

const{getVowelsCount}= require('../stringoperations.js')

test('Verify Vowels First in String', () => {

  var vowels = getVowelsCount("Browserstack is the popular testing tool");

  expect(vowels).toEqual(12);

})

test.only('Verify Vowels Second in String', () => {

  var vowels = getVowelsCount("Browserstack is a tool");

  expect(vowels).toEqual(7);

})

test.only() is added for the second test. In this case, though you execute the vowels.test.js only the second test will be executed and the first test will be skipped.

Example:

npx jest vowels.test.js

Output:

Jest vowels test

Note:

  • You can use only postfix to test(), it() or describe
  • The f prefix also performs the same operations but it is available for only it() and describe() functions. Example fit(), fdescribe() etc.

Skipping Tests Using ‘skip’ or ‘x’

There are two ways to skip a test in Jest: skip postfix or use the x prefix. Note that the x prefix is only available for it() and describe() functions. For example: you can skip the test using xit(), xdescribe(), etc. 

However, the skip postfix is available for all different functions for example test.skip(), it.skip(), etc. Let us understand with an example

From the vowels.test.js, you can modify the test to skip the second test, as shown below.

//vowels.test.js

const{getVowelsCount}= require('../stringoperations.js')

test('Verify Vowels First in String', () => {

  var vowels = getVowelsCount("Browserstack is the popular testing tool");

  expect(vowels).toEqual(12);

})

test.skip('Verify Vowels Second in String', () => {

  var vowels = getVowelsCount("Browserstack is a tool");

  expect(vowels).toEqual(7);

})

As you can see in the above code, a second test is marked with .skip(). When you execute the file, it executes only the first test, and the second test will be skipped

Example:

npx jest vowels.test.js

Output:

Output 1 passed 1 skipped

Running Tests with a Name Pattern

Jest supports running with specific patterns or keywords. For example, suppose you are working in search functionality. In that case, the test name usually contains the keyword “search” In such scenarios, you can run all the tests with a keyword search or choose a regular expression pattern.  The –testNamePattern or -t flag can be used to perform such operations. 

In the above project, consider if you want to run a test containing “Number“.  You can specify the pattern as mentioned below

npx jest --testNamePattern 'Numbers' –verbose

//Or

npx jest -t 'Numbers' –verbose

Output 3 skipped 1 passed 1

Running Jest Tests using BrowserStack Automate

BrowserStack offers a robust cloud execution platform that integrates seamlessly with a wide range of testing frameworks, from legacy systems to the latest in automation. Cross-browser and cross-platform testing, crucial aspects of modern software testing, often demand significant infrastructure investments, which can be challenging and costly to maintain. BrowserStack addresses these challenges by providing a scalable, efficient, and budget-friendly solution.

Talk to an Expert

BrowserStack Automate supports integration with the Jest framework, allowing you to easily execute your Jest tests. You can run your Jest tests in the BrowserStack cloud by making a simple configuration update—installing the browserstack-node-sdk package and creating a browserstack.yml file. 

This setup ensures that your tests are executed in real-world conditions across different browsers and platforms, offering a comprehensive testing solution. 

Interestingly, if you have a Selenium Jest framework you can easily execute them on the BrowserStack Automate platform using the below steps.

  • Install BrowserStack-node-sdk using the command npm i -D browserstack-node-sdk@latest
  • Setup access key and username with the command npx setup –username <uname –key <key>
  • Configure your browserstack.yml file.
    Browserstack.yml contains custom configurations. Refer configuration page to customize the parameter
  • Once everything is ready, just execute the tests using the below command.
browserstack-node-sdk jest src/<test_name>.test.js 

BrowserStack Automate Banner

Streamline your Jest testing with BrowserStack Automate. Run tests on real devices and browsers without the need for complex infrastructure. Quickly integrate Jest, and focus on delivering high-quality applications with ease and efficiency.

Try BrowserStack Now

Tags
Test Management Testing Tools Types of Testing

Featured Articles

Jest Framework Tutorial: How to use it?

How to Debug Jest Tests?

Boost Your Jest Testing

Run Jest tests on real devices with BrowserStack Automate. Optimize your test coverage and speed up your release cycles.