Leveraging jest for handling glob imports in files

My setup involves using webpack along with the webpack-import-glob-loader to import files utilizing a glob pattern. In one of my files (src/store/resources/module.ts), I have the following line:

import '../../modules/resources/providers/**/*.resource.ts';

However, when running a test with ts-jest, it fails and gives me this message:

Cannot find module '../../modules/resources/providers/**/*.resource.ts' from 'src/store/resources/module.ts`

It seems like jest is having trouble recognizing this import syntax. How can I configure jest to work properly with projects that use glob imports?

Answer №1

To handle globs in jest, I created a custom preprocessor to manually process the files. By controlling the processing of files and initializing the processor myself, I was able to effectively handle globs.

// config.js
module.exports = {
  transform: {
    '.': `./path/to/your/processor.js`

// processor.js
const path = require(`path`);
const glob = require(`glob`).sync;
const yourProcessor = // require your processor code - ts-jest, babel-jest, esbuild-jest, etc

module.exports = {
  process(src, filename, config, opts) {
    const dir = path.dirname(filename);
    src = processGlob(src, dir);
    return yourProcessor(src, filename, config, opts);
  },
};

function processGlob(src, dir) {
  // This function handles matching imports with globs
  return src.replace(/^import\s'(.*\*.*)';$/m, (_match, pathCapture) => {
    const matcher = /.+\..+/; 
    const files = glob(pathCapture, {cwd: dir})
      .sort()
      .filter((path) => matcher.test(path));

    return `${files.map((module, index) => `import * as module${index} from '${module}'`).join(`;`)}`;
  });
}

It's worth noting that this approach allows for one glob import per file using the map indexes for each module name. If you need multiple glob imports in one file, consider tracking a global count variable instead.

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

The ultimate guide to loading multiple YAML files simultaneously in JavaScript

A Ruby script was created to split a large YAML file named travel.yaml, which includes a list of country keys and information, into individual files for each country. data = YAML.load(File.read('./src/constants/travel.yaml')) data.fetch('co ...

Angular 8 fails to retain data upon page refresh

I have a property called "isAdmin" which is a boolean. It determines whether the user is logged in as an admin or a regular user. I'm using .net core 2.2 for the backend and Postgre for the database. Everything works fine, but when I refresh the page, ...

Ways to prevent modal from flickering during event changes

I'm struggling with a current issue and need help identifying the cause and finding a solution. The problem arises from having a nested array of Questions, where I display a Modal onClick to show Sub questions. However, when clicking on the Sub Quest ...

Guide to conditionally adding a property to an object in JavaScript

After scouring both Stack Overflow and Google for a solution, I finally stumbled upon this brilliant idea: x = { y: (conditionY? 5 : undefined), z: (conditionZ? 5 : undefined), w: (conditionW? 5 : undefined), v: (conditionV? 5 : undefined), u ...

How to trigger a function when clicking on a TableRow in React using MaterialUI

Can someone help me understand how to add an onClick listener to my TableRow in React? I noticed that simply giving an onClick prop like this seemed to work: <TableRow onClick = {()=> console.log("clicked")}> <TableCell> Content </Ta ...

"Error message pops up indicating the dispatcher is missing while using npm link with a local project

Currently, I am working on a React component library that I want to integrate into a local project for testing purposes. My initial approach was to use npm link to connect the component library with my local project. However, during this process, I encount ...

a guide on showcasing a table according to a specific column's data (CSV Path)

I currently have a table structured like this: File Name File path MyFile1.csv D:\tmp\MyFile1.csv MyFile2.csv D:\tmp\MyFile1.csv As of now, my primary table is displayed as shown below: <div class="panel-body table-res ...

React: Issue with For Loop not recognizing updates in Hook's State

Recently, I successfully created a React application that displays each word of a sentence at a user-defined time interval for fast reading. However, I am now facing a challenge as I attempt to add a pause button functionality to the app. When I press the ...

Utilizing Node and Electron to dynamically adjust CSS style properties

Having a dilemma here: I need to access the CSS properties from styles.css within Electron. Trying to use document.getElementsByClassName() won't work because Node doesn't have document. The goal is to change the color of a specific div when the ...

Attempting to showcase the data stored within MongoDB documents on my website's user interface

I am facing difficulties in showing the data stored in my database on the front end of my grocery list app, which is built using the MERN stack. I have a form that successfully sends data to MongoDB and saves it upon submission. In order to retrieve the d ...

ASP.NET ensures that the entire page is validated by the form

Is it possible to validate only a specific part of the form instead of the entire page? Currently, when I try to validate textboxes on the page, the validation is applied to all textboxes. Here are more details: https://i.stack.imgur.com/eowMh.png The c ...

Here is a guide on how to develop a PHP function that interacts with a textarea to display text in the specified color by using syntax like [color:red]

Is it possible to code a PHP function that can work alongside a textarea to display text in the specified color by using a syntax like [color:red]? This function operates in a similar manner to Facebook's @[profile_id:0] feature. ...

Client.on facing issue with receiving data upon initial connection

Currently, I am utilizing the net module in order to establish a connection between my client and server. Below is the code snippet: const Net = require('net'); client = Net.connect(parseInt(port), host, function() { co ...

Is there a similar feature to RxJs version 4's ofArrayChanges in RxJs version 5?

Currently utilizing Angular2 and attempting to monitor changes in an array. The issue lies with only having RxJs5 available, which appears to lack this specific functionality. ...

The variable within my function is not being cleared properly despite using a jQuery function

Recently, I encountered an issue with a function that displays a dialog box to ask users if their checks printed correctly. Upon clicking on another check to print, the "checked_id" value remains the same as the previously executed id. Surprisingly, this i ...

Updating a List Conditionally in React

Hello there! I am relatively new to the world of React and currently trying to grasp the concept of modifying elements within a list. Below, you'll find a straightforward example that illustrates my current dilemma. const numbers = [1, 2, 3, 4, 5]; / ...

Getting the specific nested array of objects element using filter in Angular - demystified!

I've been attempting to filter the nested array of objects and showcase the details when the min_age_limit===18. The JSON data is as follows: "centers": [ { "center_id": 603425, "name" ...

How to redefine TypeScript module export definitions

I recently installed a plugin that comes with type definitions. declare module 'autobind-decorator' { const autobind: ClassDecorator & MethodDecorator; export default autobind; } However, I realized that the type definition was incorrec ...

When the menu active item is clicked, the header will automatically scroll to the top

I've implemented a sticky header using CSS and JavaScript along with a mega menu. However, I've encountered an issue where when scrolling to the bottom and clicking on the "more" link in the dropdown, the page scrolls back to the top. This is the ...

Improving the testing of Express routes using a test database in PostgreSQL

I've been working on improving my skill at writing tests for Node.js APIs, particularly in relation to a recent project where I interact with an endpoint /api/v1/restaurants that provides data in the form of an array of objects. Below is the functiona ...