Execute Jest tests exclusively on the directory you are currently in

When I run Jest on my machine by typing jest from the terminal, it automatically executes tests from parent folders as well. However, I want to only run tests from the current folder.

For example, if I navigate to c:/dev/app in the terminal and enter a command like some-jest-command, I expect it to only run files with the .test.js extension present in the app folder. Currently, running the jest command from the app folder includes tests from parent folders, which is not what I want.

Answer №1

To execute tests from a specific directory, utilize the --testPathPattern jest flag. Ensure to include the folder path when setting up the npm script. Add the flag in your npm scripts within package.json as shown below:

"scripts": {
    ....
    "test:unit": "jest --testPathPattern=src/js/tests/unit-tests",
    "test:integration": "jest  --testPathPattern=src/js/tests/integration"       
    ....
},

If you want to monitor for changes as well, add the watch flag:

{
  ...
  "test:unit": "jest --watch --testPathPattern=src/js/tests/unit-tests",
  ...
}

Once set up, navigate to the command line, switch to your project directory, and run either the unit test:

npm run test:unit

or integration tests:

npm run test:integration

Answer №2

By default, Jest will automatically test all files in the directory where the package.json file is located.

For example, if your project is in the folder c:/dev/app and your package.json is in c:, running the command npm test will run tests recursively starting from c:. To focus on specific folders like c:/dev/app, you can use the command npm test dev/app.

Answer №3

If you want to restrict Jest testing to a specific directory and specify the type of files to be read (for example: 'ExampleComponent.test.js' with Jest version @24.9.0), you need to define the exact "testMatch" in your jest.config.json or package.json under the "jest" section like this

"testMatch": [ "<rootDir>/src/__tests/**/*.test.js" ]
. In my scenario, this testMatch pattern targets all files starting with .test.js in tests subdirectories while ignoring other files like 'setupTest.js' and other .js files in the 'mocks' subdirectory located within the 'tests' directory, hence my 'jest.config.json' appears as follows

    {
        "setupFiles": [
            "raf/polyfill",
            "<rootDir>/setupTests.js"
        ],
        "snapshotSerializers": [
            "enzyme-to-json/serializer"
        ],
        "moduleNameMapper": {
            "^.+\\.(css|less|scss|sass)$": "identity-obj-proxy"
        },
        "testMatch": [
            "<rootDir>/src/__tests/**/*.test.js"
        ]
    }

You can adjust the regular expression used for 'testMatch' according to your requirements.

Just a side note: This is applicable for [email protected] && [email protected] if it's relevant to anyone.

I trust that this information will prove helpful to someone, best wishes to all.

Answer №4

To execute tests for specific files in your project, navigate to the root directory and use the command jest <substring of files>. This will run only the test files that contain the specified substring.

$ jest /libs/components
> [PASS] /libs/components/button.tsx

Answer №5

--package.json

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

--jest.config.js

module.exports = {
    "testMatch": [
        "<rootDir>/tests/unit/*.test.js"
    ]
  }

Answer №6

Testing instructions:

To test a specific folder, use the following commands:

yarn:

yarn test nameoffolder

npm:

npm test nameoffolder

For instance, if you have a directory called widget and wish to only run tests within the widget folder, execute this command.

yarn:

yarn test widget

npm:

npm test widget

Answer №7

If you want to focus on a specific section within a test file, you can use the -t option when running jest as long as that section has a unique describe statement.

For example, let's say we have the following test file:

...

describe('specific section XYZ', () => {
    it('test A', () => { ... });
    it('test B', () => { ... });
    it('test C', () => { ... });
    it('test D', () => { ... });
});

...

To run only the tests within the "specific section XYZ", you can use this command:

jest -t "specific section XYZ"
.

Here is an explanation of the -t flag:

-t, --testNamePattern        Run only tests with a name that matches the regex pattern.

Answer №8

Suppose you are currently in the directory path /project/homepage; to run only the tests within the homepage/ directory using jest, do the following:

npx jest --watch homepage

If typing the directory name is a hassle, utilize the subshell command $(basename "$PWD"), as shown below:

npx jest --watch $(basename "$PWD")
  • The command $(basename "$PWD") extracts the base name of the current working directory ($PWD).
    • The basename function removes the directory path and retains only the final component (i.e., the directory name itself, such as homepage from /project/homepage).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message in Angular 2, Problem found in inline template while utilizing eval() function

<li *ngFor="let pdfifRecord of pdf.ifRecord;let i=index"> <p>{{eval(pdfifRecord.labelMsg)}}</p> </li> I need to show the output of the eval function. Encountering an error message: Error in inline template c ...

Animation effect in Jquery failing to execute properly within a Modal

I have developed a small jQuery script for displaying modals that is both simple and efficient. However, it seems to only work with the fadeIn and fadeOut animations, as the slideUp and slideDown animations are not functioning properly. I am unsure of the ...

Displaying dates in Meteor Handlebars using `{{ timestamp }}` braces

Looking to shorten the timestamp output in Meteor's Handlebar bracers. How can you convert {{ timestamp }} from Thu Jul 25 2013 19:33:19 GMT-0400 (Eastern Daylight Time) to just Jul 25? Attempted using {{ timestamp.toString('yyyy-MM-dd') } ...

What is the process for creating an index signature for a type alias representing a Map in Typescript?

Suppose I have a custom type for a Map as follows: type MyCustomMap = Map<string, number>; Is there any way to add an index signature to this type so that I can set key-value pairs after initializing it? I have been able to achieve this with types ...

Updating the image source using Javascript

I've implemented a timer in my JavaScript that animates something on a website. While everything is functioning perfectly, I am struggling to change an image whenever the animation is triggered. The script utilizes jQuery: if(options.auto && ...

"Maintaining Consistency: Ensuring The First Row is Repeated on Every

When trying to save a PDF using jspdf, I encountered an issue with tables in my HTML. The tables do not have headers, but JsPDF is automatically repeating the first row of the table on every page, causing overlap. I don't want headers on every new pag ...

Creating a TypeScript shell command that can be installed globally and used portably

I am looking to create a command-line tool using TypeScript that can be accessed in the system's $PATH once installed. Here are my criteria: I should be able to run and test it from the project directory (e.g., yarn command, npm run command) It must ...

Show live updates in the input field

I'm struggling to get an input's results to update in real time within another disabled input field. Here is the code I'm working with: var inputBox = document.getElementById('input'); inputBox.onkeyup = function(){ document. ...

Need help implementing the disableGutters property on MTableToolbar?

I am currently using react material-table and I would like to customize the default toolbar styles by passing the prop disableGutters={true}, similar to how it's done in material-ui toolbar. Below is the code snippet that I have tried: <MaterialTab ...

The error message "gulp error - _.flattenDeep is not a function when using gulp.watch" is indicating

Whenever I run a watch task, why am I encountering the TypeError: _.flattenDeep is not a function error? Below is the content of my gulpfile.js : var gulp = require('gulp'); var sass = require('gulp-sass'); var sourcemaps = require(&a ...

Leveraging current state data (from store) in ReactJS promptly

Working in React with Flux and faced with a challenge. Within my component, I have a function triggered by a click event: onClickEventEdit: function(itemId) { ScheduleActions.getEventById(itemId) // sets the retrieved data into `currentEventById ...

Issue with loading HTML file correctly in Django

I have been attempting to integrate my Django app with an admin dashboard from a repository on GitHub. After successfully logging in, the app redirects to the dashboard, but only the HTML part loads and none of the fancy features are visible on the dashboa ...

Using three.js to create a rotating analog clock in Javascript

I currently have a traditional clock displayed in my setting that I want to synchronize with the current time. I am able to keep the clock running by calculating each hand's rotation every second, but I am encountering peculiar issues with the minute ...

Browser encountering HTTP response that has been shorted extensively

When making an HTTP post request using axios, I am encountering an issue where the body of the response is a large 4MB string. axios({ method: 'POST', url: url, data: data, headers : headers, }) .then(function (response) { co ...

Using Express and React with Socket.io

I am currently working on setting up a basic WebSocket connection using Socket.io, Express, and ReactJS. Below is the code for the server: const express = require('express'); const socket = require('socket.io'); const path = require(& ...

Is there a way to show a loading indicator while waiting for ajax to finish loading?

While waiting for my messages to finish loading, I'd like to display a loading spinner. The loading spinner is implemented in my Message.vue: import backend from '...' export default { mounted: function() { this.loadMessages(); }, ...

Is it possible for links to remain clickable even if they pass underneath a div

I have implemented a shadow using a div element to cover some content beneath it. However, I am facing an issue where the div that is under the shadow cannot be interacted with. Is there any solution to this problem? Thank you ...

Making a Dialog resizable with jQuery's Resizable Helper

Is there a way to implement the Helper feature from jQuery Resizable, which only shows a frame while resizing the container, in a Dialog? ...

"Trouble with Express.js: CSS isn't loading, yet HTML displays

Click here to view folders and files server.js is the code I have created so far //importing packages const express = require('express'); const admin = require('firebase-admin'); const bcrypt = require('bcrypt'); const path = ...

Guide to verifying all chosen options in a multiple select field using EJS

I am looking for the most effective way to check all selected options in my select dropdown when data is being edited. Here is an example of my select dropdown that supports multiple selections: <select name="tags[]" class="multi-select" multiple="" i ...