Using the -t or --testNamePattern in Jest will execute all tests

Currently, I have set up my testing framework using jest and ts-jest based on the guidelines provided by the ts-jest documentation.

When I execute the command yarn test --listTests, I can identify the specific test file I intend to run: processNewUser.ts located within a __test__ folder in my project.

I have successfully executed this test individually using the command

yarn test --testPathPattern='processNewUser'
.

However, when I attempt to specify a particular test by its name using commands like

yarn test --testNamePattern='Processes new user. Auth'
, all tests are triggered, including those not matching the specified name.

I have tried various combinations of syntax such as: yarn test -t="Auth", yarn test -t Auth,

yarn test --testNamePattern "Auth"
, jest Auth, jest -t="Processes", and numerous other permutations, but none have been successful. I also attempted naming a describe function wrapper instead of a test, but with no success either.

The contents of my tsconfig.json file are as follows:

{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    "outDir": "dist",
    "sourceMap": true,
    "allowJs": true,
    "strict": true,
    "noImplicitAny": false,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "removeComments": false,
    "skipLibCheck": true,
    "allowSyntheticDefaultImports": true,
    "lib": [
      "ES2020.Promise",
      "ES2015.Iterable",
      "ES2015.Symbol.WellKnown"
    ],
  },
  "include": ["src/**/*"],
}

Additionally, here is the content of my jest.config.ts file:

import type {Config} from '@jest/types';
const config: Config.InitialOptions = {
  clearMocks: true,
  coverageDirectory: 'coverage',
  coverageProvider: 'v8',
  moduleFileExtensions: ['js', 'json', 'jsx', 'ts', 'tsx', 'node'],
  preset: 'ts-jest',
  setupFiles: ['dotenv/config'],
  setupFilesAfterEnv: ['./jest.setup.js'],
  testEnvironment: 'node',
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
    '^.+\\.ts?$': 'ts-jest',
  },
  transformIgnorePatterns: ['/node_modules/', '\\.pnp\\.[^\\/]+$'],
  
}

export default config;

My Yarn script only consists of:

"test": "jest",

One of my objectives is to categorize tests with tags like auth so that I can easily run all authentication-related tests. Can anyone provide assistance or guidance on achieving this?

Answer №1

After encountering the same issue, I discovered that the error actually stemmed from my attempt to concatenate the remaining code with npm. Strangely, npm did not include all the necessary additional commands in the package.json file along with the script.

To resolve this, I switched to using yarn to run the code.

example

Answer №2

The function responsible for filtering tests by name can be found here:

  if (config.testNamePattern) {
    const testNameReg = new RegExp(config.testNamePattern, 'i');
    environment.specificationFilter = (specification: Specification) => testNameReg.test(specification.getFullName());
  }

Note that it compares the regular expression generated with the full name of each test case. This includes the name of the test suite and all the names of the describe blocks surrounding it.

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

When using React with TypeScript, there seems to be an issue where using history.push to change the URL results in rendering the 404 page instead

I have gone through all the previous answers but none of them could solve my problem. I am new to React and currently working on a personal project where I use React with TypeScript, Redux, and Material UI. For some reason, when I try to redirect from ins ...

What is the process of declaring a method within a subclass and then retrieving it from a method within the parent class using Typescript?

I am currently working with this TypeScript code snippet: abstract class Base { static actions:Record<string,unknown> static getActions () { return this.actions } } class Sub extends Base { static actions = { bar:(bar:string ...

Harness the Power of Generics in TypeScript for Automatic Type Inference

function execute<T>(operation1: (input: T) => void, operation2: (input: { key: string }) => T): void {} execute((params) => {}, () => 23); // The params here can be correctly inferred as number execute((params) => {}, (arg) => 23) ...

Integrating fresh components into a JSON structure

I've been attempting to insert a new element into my JSON, but I'm struggling to do it correctly. I've tried numerous approaches and am unsure of what might be causing the issue. INITIAL JSON INPUT { "UnitID":"1148", "UNIT":"202B", "Sp ...

Is there a way to trigger validation with a disabled property?

My form element is set up like this: <input type="text" id="country" formControlName="Country" /> The form group looks like this: this.myForm = this.formbuilder.group({ 'Country': [{ value: this.user.Country, disabled: this.SomeProperty= ...

I need to search through a tree structure in typescript based on a specific value without encountering a maximum stack call exceeded error

How can I perform a value-based search on a complex tree structure in TypeScript without encountering the maximum stack call exceeded error? I am attempting to navigate through an expandable tree using TypeScript, and I will provide the code snippet below ...

Evolution of ReactJS state over time

When working with React, I wanted to increment a state variable called progressValue by 0.1 every 500 ms until it reaches 100. Here's what I initially tried: const [progressValue, setProgressValue] = React.useState<number>(0) const tick ...

Creating a custom Higher Order Component to seamlessly connect react-relay and react-router using TypeScript

Hey there! So, my Frankenstein monster project has decided to go rogue and I'm running out of hair to pull out. Any help would be greatly appreciated. I've been working on setting up a simple app with React, React-Router, React-Relay, and Typesc ...

Angular2 Eclipse: Eclipse Oxygen's HTML editor detects TypeScript errors in real-time

After installing the Eclipse Oxygen plugin for Angular2, I created a project using the Angular CLI and opened it in Eclipse. However, when trying to convert the project to an Angular project, I couldn't find the option under configuration. Instead, th ...

Expanding Angular FormGroup Models with TypeScript

I've developed a foundational model that serves as a base for several other form groups. export class BaseResource { isActive: FormControl; number: FormControl; name: FormControl; type: FormControl; constructor( { ...

Is there a way to execute Selenium test scripts without the need for local installation or running?

I am in search of a way to create a central 'hub' for Selenium within my workplace so that every employee can easily access it. For example, if Tester A writes test scripts, Person B should be able to run them without manually transferring the sc ...

Unable to modify the value of a key within an object using TypeScript

I'm struggling to update the value of a key within an object using TypeScript. Here's an overview of the types I'm working with: export enum BAR_TYPES { apple = "apple", banana = "banana" } export type BarTypes = ...

What is the best way to insert CSS code into a custom Vue directive file?

I need a solution that applies a gradient background to the parent div in case an image fails to load. I've attempted to create a directive for this purpose: export default { bind(el: any, binding: any) { try { ..... ...

Utilize the reducer from another slice in Redux Toolkit

I am working with an authSlice const authSlice = createSlice({ name: 'authStore', initialState, reducers: { logout(state = initialState) { return { ...state, isAuthenticated: false }; }, }, extraReducers: (builder) => { ...

Is it feasible to securely remove an item from an array within an object without the need for any assertions in a single function?

My interest in this matter stems from curiosity. The title may be a bit complex, so let's simplify it with an example: type ObjType = { items: Array<{ id: number }>; sth: number }; const obj: ObjType = { sth: 3, items: [{ id: 1 }, { id: 2 } ...

Navigating through nested JSON Objects for dropdown functionality in Angular 6 - a step-by-step guide

Currently, I am facing a challenge in Angular 6.0 where I am trying to use HttpClient to iterate through JSON data retrieved from a local file within my assets folder. Below is the sample JSON Data: [{ "configKey": [{ "user1": [{ ...

Challenges when building a production version of an Expo app with Typescript

Attempting to perform a local production build, I ran expo start --no-dev --minify. Only the initial template file displays, stating "Open up App.tsx to start working on your app," and none of my work is visible... Has anyone else encountered this issue a ...

Retrieve both the name and id as values in an angular select dropdown

<select (change)="select($event.target.value)" [ngModel]="gen" class="border border-gray-200 bg-white h-10 pl-6 pr-40 rounded-lg text-sm focus:outline-none appearance-none block cursor-pointer" id="gend ...

Will the async pipe activate onPush change detection in Angular?

I have searched various sources for the question above, but I am finding conflicting answers. For example, on Angular University's website, it is mentioned that change detection is triggered when the async pipe receives a new observable value. However ...

Tips on using constructor functions and the new keyword in Typescript

This is a demonstration taken from the MDN documentation showcasing the usage of the new keyword function Car(make, model, year) { this.make = make; this.model = model; this.year = year; } const car1 = new Car('Eagle', 'Talon TSi&apos ...