Searching for nicknames in a worldwide Jest arrangement?

Before running all test cases, I need to execute certain tasks only once. To achieve this, I have created a global function and specified the globalSetup field in my Jest configuration:

globalSetup: path.resolve(srcPath, 'TestUtils', 'globalSetup.ts'),

However, the use of aliases within globalSetup triggers an error with Jest unable to find them.

Is there a way to ensure that globalSetup runs only after resolving the aliases?

Here is an overview of my Jest configuration:

module.exports = {
  rootDir: rootPath,
  coveragePathIgnorePatterns: ['/node_modules/'],
  preset: 'ts-jest',
  setupFiles: [path.resolve(__dirname, 'env.testing.ts')],
  setupFilesAfterEnv: [path.resolve(srcPath, 'TestUtils', 'testSetup.ts')],
  globalSetup: path.resolve(srcPath, 'TestUtils', 'globalSetup.ts'),
  globals: {},
  testEnvironment: 'node',
  moduleFileExtensions: ['js', 'ts', 'json'],
  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>/' })
};

While running testSetup resolves aliases before every test case as expected, the same does not apply for globalSetup.

Any suggestions on how to resolve this issue?

Answer №1

To successfully implement this solution, I included tsconfig-paths/register at the beginning of my globalSetup file:

// globalSetupFile.ts

import 'tsconfig-paths/register';
import { Item } from './location-with-aliases';

export default async () => {
  await Item.doGlobalSetup();
}

Ensure that you have installed tsconfig-paths in your project.

Answer №2

Regrettably, it appears that a solution for this issue is not available based on the discussions in the following comments thread: https://github.com/facebook/jest/issues/6048

The main point to note is that globalSetup operates independently of the Jest ecosystem, which means it will not recognize aliases and similar configurations.

However, there are various workarounds that can be implemented. For instance, if your npm run test command looks like this:

"test": "jest --config config/jest.config.js --detectOpenHandles --forceExit"

You could consider modifying it to include an additional step before running Jest:

"test": "node whateverBeforeJest.js && jest --config config/jest.config.js --detectOpenHandles --forceExit"

Answer №3

It's worth noting that globalSetup operates independently of the Jest ecosystem and doesn't have access to aliases.

My approach to addressing this issue involved the following folder structure:

src
└── __tests__
    └── client 
    └── server
        └── tsconfig.json
        └── _config
            └── jest.config.ts
            └── jest.global.setup.ts
            └── jest.global.teardown.ts
        └── controllers
            └── public.test.ts
            └── ...more
└── client
    └── ...more
└── server
    └── controllers
    └── ...more
└── tsconfig-base.json
package.json

Within package.json, I included the necessary dependencies:

{
    ...
    "dependencies": {
        ...
    },
    "devDependencies": {
        "supertest": "^6.3.4",
        "ts-jest": "^29.1.2",
        "tsconfig-paths": "^4.2.0",
        "typescript": "^5.4.2",
        ...
    },
    "_moduleAliases": {
        "@/controllers": "bin/controllers",
        "@/enums": "bin/enums",
        "@/exceptions": "bin/exceptions",
        "@/interfaces": "bin/interfaces"
    },
    ...
}

The tsconfig-base.json file was configured as follows:

{
    "compilerOptions": {
        // Compiler options here
    },
    "include": [
    ],
    "exclude": [
        "**/node_modules/*",
        "bin",
        "public"
    ]
}

Additional configurations were made in jest.config.ts, jest.global.setup.ts, and public.test.ts files to address the alias recognition issue.

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

Tips for exporting/importing only a type definition in TypeScript:

Is it possible to export and import a type definition separately from the module in question? In Flowtype, achieving this can be done by having the file sub.js export the type myType with export type myType = {id: number};, and then in the file main.js, i ...

Using Typescript and webpack to detect variables that are defined in the browser but not in Node environment

My goal is to create a package that can be used on both servers and clients with minimal modifications required. Some libraries are available in Node but not in a browser, while others are accessible in a browser but not in Node. For instance, when utili ...

The inclusion of a content editable feature within a carousel is leading to unexpected event propagation

I am dynamically creating an editable div using the code snippet below. <div class='reflection-field' contenteditable="true" data-number="${index}"></div> Expected Outcome: When I click on the generated div, I anticipate that the c ...

Encountering an error where property 'onClicked' is not defined when attempting to utilize chrome.action or chrome.browserAction in Chrome

I am currently developing a Chrome extension that will automatically redirect me to a specific URL when I click on the browser action icon. Here is the code snippet that I am trying to implement: chrome.browserAction.onClicked.addListener However, I am ...

Angular 8 encountered a 404 (Not Found) error when trying to POST to http://localhost:4200/assets/data/students.json

I'm currently working on a project that involves fetching array data through HTTP and should also allow for the addition of new arrays using HTTP. However, every time I attempt to post a new array, I encounter the following error: POST http://local ...

Verify if the nested JSON object includes a specific key

Currently, I am grappling with a dilemma on how to determine if within a deeply nested JSON object, featuring numerous unknown arrays and properties, lies a specific property that goes by the name "isInvalid". My objective is to identify this property and, ...

Unexpected Token E encountered in the Twitter stream.on function

I'm currently in the process of setting up a search button on my web application that will pull all Twitter tweets related to the search input using the streaming API. Below is my client-side code: <form class="navbar-form navbar-left" role="sear ...

Animating with JQuery utilizing a dynamic attribute

We are facing a challenge with animating multiple divs that share the same class name and have different attribute values: <div class="chart-bar" style="width:10%;" bar-width="100%"></div> <div class="chart-bar" style="width:10%;" bar-wid ...

Implementing React and Material UI - Customizing Navigation Buttons/Links according to Routes

The following code snippet represents the main entry point of a React app, app.js, which includes the router endpoints. Below the app.js code, you will find the code for a Nav component, which serves as the navigation menu. I am looking to structure this ...

"Despite the null date in Node.js, the validation for expiration dates less than Date.now() is still being enforced

I am currently working on implementing validation for evaluating the finish status. However, my validation is encountering a problem with the "null" value of expiresAt. It should indicate that the evaluation has been successfully completed. The issue lie ...

Build a Node.js application with Express to host static files

I am attempting to provide my static files "web.html" and "mobile.html", but I want them to be served only if the user is accessing from a web or mobile device. After some research, I came up with this code: var express = require('express'); va ...

Converting Json arrays to HTML tables using the window.chrome.webview.addEventListener feature with a Server Delphi Application

My Delphi application is sending Json data to the embedded Edge browser, but Javascript is reporting a parser error. https://i.sstatic.net/Z2BUq.png https://i.sstatic.net/0IIzJ.png When I modify the value for Sender.DefaultInterface.PostWebMessageAsJson ...

What is the best way to extract all image URLs from a website using JavaScript?

There are various methods to retrieve image src urls using JavaScript, such as utilizing document.images or by targeting all img elements and fetching their src attributes. However, I am currently unable to extract the image urls specified within CSS styl ...

Loss of value in .net Jquery CheckBox onchange event

My JQuery code for CheckBoxes is causing some unexpected behavior: $(document).ready(function () { $('#chk_AGVS').change(function () { if ($(this).is(":checked")) { '<%Session["chkAGVS"] ...

What is the best way to access the data stored within a Promise object in a React application?

Below is the snippet of my code that handles parsing application data: async function parseApplication(data: Application) { const fieldGroupValues = {}; for (const group of Object.keys(data.mappedFieldGroupValues)) { const groupValue = data.mappedF ...

Using AngularJS to convert a JSON object into an array

Hey there, I've got a JSON return object that looks like this: color_selected = [ { id: 4}, { id: 3} ]; Any tips on how I can convert it to the following format? color_selected = [4,3] Appreciate any help or s ...

Hiding loading spinner in Ionic 2 upon iframe completion

I need to embed an external webpage in my app using an iframe. I have successfully implemented a loading animation while the iframe is loading, but I am unsure how to hide the animation once the iframe content has loaded. Unfortunately, I am unable to edit ...

Using a pool.query with async/await in a for-of loop for PostgreSQL

While browsing another online forum thread, I came across a discussion on using async/await with loops. I attempted to implement something similar in my code but am facing difficulties in identifying the error. The array stored in the groups variable is f ...

What is the command line method for running ESLint in flat configuration?

When using the flat config for eslint.config.js, how can I lint *.js files recursively from the command line? 1 In the past with eslintrc.js or eslintrc.json, I have used npx eslint . --ext .js, as mentioned here. Up until now, it has always worked withou ...

What is the method to remove curly brackets from a different data category?

If I have a type like this type Z = {a: number} | {} | {b: boolean} | {c: string} | ...; Is there a way to get the same type but without {}? type Y = Exclude<Z, {}>; ⇧This will result in Y = never, because all variants can be assigned to {} and a ...