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

What is the best way to integrate Emotion styled components with TypeScript in a React project?

Currently, I am delving into TypeScript and attempting to convert a small project that utilizes Emotion to TypeScript. I have hit a roadblock at this juncture. The code snippet below export const Title = styled.div(props => ({ fontSize: "20px", ...

Angular integration problem with aws-amplify when signing up with Google account

I am attempting to integrate AWS-Amplify(^4.3.0) with angular-12 and typescript (4.3.5). I have followed the documentation to configure amplify properly, but when trying to start the app, I encountered some amplify errors as shown below. Warning: D:\G ...

Using ngIf for various types of keys within a JavaScript array

concerts: [ { key: "field_concerts_time", lbl: "Date" }, { key: ["field_concert_fromtime", "field_concert_totime"], lbl: "Time", concat: "to" }, { key: "field_concerts_agereq", lbl: "Age R ...

Issue with Angular ngFor binding. What could be causing this error to occur?

I have a main component called DOCUMENT. This document receives a URL segment and retrieves an array of associated objects from my database. Then, using @Output() documents = new EventEmitter() and an @Input() in a DOCUMENT VIEW component, I loop through t ...

``There are problems with parsing JSON data due to the error message indicating the presence of unexpected

I am encountering an issue with displaying values from objects stored as string[] in appwriteDB. When trying to use *ngFor to iterate through the data, I faced difficulties. Despite attempting to convert the orderItems using JSON.parse(), the process faile ...

Exploring the process of dynamically incorporating headers into requests within react-admin

Currently utilizing react-admin with a data provider of simpleRestProvider. I am in need of a solution to dynamically add headers to requests based on user interactions. Is there a way to achieve this? Appreciate any assistance. Thank you! ...

Angular application triggering multiple subscribe method calls upon a link click event

Here is the code for my navbar component: <li *ngFor="let item of menu"> <a *ngSwitchCase="'link'" routerLinkActive="active" [routerLink]="item.routerLink" (click)="Navigation(item.title)&q ...

How can Mui typescript be extended with a unique wrapper that includes a `component` property?

I recently created a unique wrapper component: import Box, { BoxProps } from "@mui/material/Box"; type CustomWrapperProps = { id: string } & BoxProps const CustomWrapper = (props: CustomWrapperProps) => { const {id, children, ...rest ...

Can you please provide guidance on setting the return type to React.StatelessComponent?

This code is functioning correctly: import * as React from 'react'; export default (props: any): JSX.Element => { return ( <h1>{props.children}</h1> ) } However, this snippet is causing an error: import * as React from ...

Mastering the mapping function in ReactJs for a Map<string, boolean> data structure

Just a quick question, I seem to be stuck on this. Here is my Map: public checkboxOptions: Map<string, boolean>; In the render() function, I want to loop through it like this: renderCheckboxMenu(): any { let menu = <div className={`${style[ ...

Tips for identifying and handling errors in Playwright

I'm going crazy trying to handle a TimeoutError that I know is coming. Currently, I'm testing the Hidden Layers scenario from UI Testing Playground in Playwright Node.js and I want to see if there's a way to prevent the TimeoutError from cau ...

When TypeScript in IntelliJ fails to generate JavaScript files after enabling the tsconfig declaration

In my tsconfig file, I have the following setup: { "compilerOptions": { "module": "ESNext", "target": "es6", "sourceMap": true, "rootDir": "./&qu ...

Is there a way to incorporate TypeScript type definitions into a JavaScript module without fully transitioning to TypeScript?

Although the title may be a bit confusing, it encapsulates my query in a succinct manner. So, here's what I'm aiming to achieve: I currently have an npm module written in JavaScript, not TypeScript. Some of the users of this module prefer using ...

Is it possible to incorporate an interface with a named function in TypeScript (function declaration)?

Just dipping my toes into Typescript and experimenting with interfaces for my functions: interface StringFunction { (arg1: string): string } I managed to associate this interface with a function by declaring it as a variable: let testFunction: Strin ...

I am looking to implement tab navigation for page switching in my project, which is built with react-redux and react-router

Explore the Material-UI Tabs component here Currently, I am implementing a React application with Redux. My goal is to utilize a panelTab from Material UI in order to navigate between different React pages. Whenever a tab is clicked, <TabPanel value ...

Best practices for testing function and internal statement following form submission handler in jest and enzyme for react applications

Working on a React functional component with a form that includes a form handler triggering onSuccess and onFailure functions, where onSuccess function closes the modal. Next, I am in need of writing tests for the onFailure, onSuccess functions, as well a ...

What is the best way to set up a variable in Typescript that will be assigned the value of an asynchronous request once it is completed?

As a newcomer to typescript, I encountered an issue that hadn't occurred in my previous project. It appears that declaring a variable before an API request inside a try-catch block leads to typescript errors when attempting to use this variable after ...

Currently, I am collaborating on an e-commerce endeavor utilizing TypeScript and sanity.io, encountering an issue along the way

Encountering an Uncaught TypeError message: Cannot read properties of undefined (reading '_ref'). While attempting to utilize code for displaying API content on a webpage, what might be causing this issue and how can it be resolved to successful ...

The click listener triggers a single time when a render method is nested within it

When I have a click listener on a button that resets the innerHTML of a div with a render method, the listener fires every time I click if I take out the render function. However, if the render function is included, the listener does not fire multiple time ...

Heroku build is reporting that it cannot locate the `@types` in the package.json file

Encountered Heroku Build Error - TSError: ⨯ Struggling to compile TypeScript: - src/server.ts(1,38): error TS7016: File declaration for module 'express' not found. '/app/node_modules/express/index.js' is implicitly of type 'any&a ...