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

Issue with Orgchart JS: The requested resource does not have the 'Access-Control-Allow-Origin' header present

Currently, I am developing a program to create organization charts using orgchart.js and simple PHP. This project does not involve any frameworks, but unfortunately, I encountered the following error: CORS policy is blocking access to XMLHttpRequest at & ...

What type of response does XHR provide when there is no connection available?

Imagine I launched Google Chrome and its corresponding extension. The extension relies on the XmlHttpRequest object for functionality. However, upon starting the browser, I realized there is no internet connection available. In this scenario, what will t ...

The Console.Log function will not run if it is placed within the RXJS Tap operator

In my current setup, I have the following observables: this.authenticationService.isSignedIn() -> Observable<Boolean> this.user$ -> Observable<UserModel> I am in need of checking a condition based on both these observables, so I attempt ...

Guide to importing images (.svg, .png) into a React component

I'm currently facing an issue trying to upload an image file in one of my React components using webpack. My project is already set up with web pack. Below is the code snippet for the component: import Diamond from '../../assets/linux_logo.jpg& ...

Unexpected issue with Ajax form submission when using the submitHandler function in Jquery

I am faced with the challenge of validating a form using the jQuery Validation Plugin and submitting data to a database without refreshing the page. Despite marking all fields in my form as required, the issue arises where empty fields are still submitted, ...

Guide to downloading a file from a byte base64 in Vue.js

I am dealing with a byte base64 string let data = 'UEsDBBQABgAIAAAAIQBi7...' If I want to download the file from this byte base64 in vue js, what should I do? Any suggestions or solutions would be greatly appreciated :') ...

Dynamic website content updating using AJAX and PHP with seamless table refreshing

I'm really struggling to find a solution for this issue and it's frustrating that I can't even find one example! So, here's the situation: I have a monitoring system (PHP / MySQL) that is refreshed using Javascript. The problem is that ...

Obtaining distinct form control values for replicated form fields with Angular

Issue with Dynamic Form Duplicates: I am currently working with a reactive form that has two fields - name and value. There is an add button that duplicates the form by copying these fields. The challenge I am facing is with updating the values of the dup ...

transition from jQuery to Zepto

I have been utilizing multiple jQuery plugins in my codebase... Recently, I decided to switch over to Zepto, but encountered an issue Uncaught TypeError: Object function (a,b){return A.init(a,b)} has no method 'data' when checking the console ...

Transfer data via ajax to the controller

I need assistance with storing a file in my database using Tabulator without having a form already created. I am currently creating a simple input element like this: var editor = document.createElement("input");. After clicking the file, it trigg ...

Ways to differentiate between a desktop browser width of 1024px and a tablet width of 1024px with the help of jquery

So here's the issue I'm dealing with: I have scroll-based animation functions set up for desktop browsers, and different animations in place for tablet browsers. The challenge is to make these functions work on a desktop with a 1024px dimension. ...

Close pop-up upon successful AJAX response in ASP.NET MVC

I have a modal in my view that allows me to create a new record in the database. The view for this functionality is contained within a partial view. Below is the code for the view: <script src="~/Scripts/jquery-3.1.1.js"></script> To han ...

Building a straightforward expandable/collapsible tree view with AngularJS by utilizing a particular data format

Seeking a tree view control that displays as follows: http://plnkr.co/edit/JAIyolmqPqO9KsynSiZp?p=preview +Parent child +Parent child child child child +Parent child child child child child chil ...

A compilation of web browsers and their compatible versions for the SVG engine

I recently encountered an issue with the org chart I created using getorgchart. Everything was running smoothly until I tested it on IE8. It turns out that getorgchart relies on the SVG engine for rendering, which is not supported by IE8. I attempted to ...

Looking for guidance on converting JS code to TypeScript? Let's tackle this TS test together!

I am facing the challenge of encapsulating a very complex SDK into a layer of code. I have attempted to utilize union and index types for this task, and below is a demo that I have created. How can I implement the bar method in TypeScript to pass the conso ...

One efficient way to iterate through an object and modify its values in a single line of code

_shop: { [key: string]: string[] } = { fruits: ['Apple', 'Orange'], vegetables: ['Tomato', 'Onions'] } Can a one-liner code be used to modify the values of _shop and return it in a specific format? The desired outp ...

Concealing my menu with overflow-x: hidden on the body is not an option

Despite setting overflow-x: hidden on the body element, I'm still experiencing horizontal scrolling and can't seem to find a solution. I've searched online for solutions without success. That's why I'm reaching out here in hopes o ...

Incorporating a Streamlit Application into an Established React.js Project via an iFrame

I am in the process of incorporating a Streamlit app into my existing React.js application to take advantage of its data analysis and visualization features. Can this integration be accomplished using an iFrame? Has anyone successfully embedded a Streamlit ...

Duplicate entries in the angular-ui Calendar

I've implemented the Angular-UI calendar to showcase some events. My activity controller interacts with the backend service to fetch the data, which is then bound to the model. //activity controller $scope.events = []; Activities.get() ...

Updates made in the type declaration files are not being displayed

I'm currently working on an express app and I have been trying to add a new property to the Request's class instance. To achieve this, I created a type.d.ts file at the root of my project that looks like this: type User = { name: string } de ...