Issue with Jest: receiving error message "Module cannot be found" despite having the package installed

Recently, I went through a cleanup and update process for a private package to make it compatible with Vite.

Initially, the package.json file had the following structure:

{
  "name": "@myRegistry/my-package",
  "version": "7.15.1",
  "main": "./dist/index.js",
  "typings": "./dist/index.d.ts",
  "scripts": {
    "build": "tsc --outDir dist/",
    "build:docs": "typedoc ./index.ts",
    "test": "jest",
    "prepublishOnly": "npm run build"
  },
  "dependencies": {
    "portable-fetch": "^3.0.0"
  },
  "devDependencies": {
    "@types/jest": "^25.2.1",
    "@types/node": "^13.13.0",
    "jest": "^25.4.0",
    "ts-jest": "^25.4.0",
    "typedoc": "^0.20.36",
    "typescript": "^3.8.3"
  },
  "jest": {
    "transform": {
      "^.+\\.tsx?$": "ts-jest"
    },
    "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ]
  }
}

After the cleanup, the modified package.json looks like this:

{
  "name": "@myRegistry/my-package",
  "version": "7.16.0",
  "type": "module",
  "files": [
    "build"
  ],
  "main": "./build/my-package.js",
  "module": "./build/my-package.js",
  "types": "./build/index.d.ts",
  "exports": {
    ".": {
      "import": "./build/my-package.js"
    }
  },
  "scripts": {
    "build": "tsc && vite build",
    "docs": "typedoc ./src/index.ts"
  },
  "devDependencies": {
    "typedoc": "^0.23.21",
    "typescript": "^4.6.4",
    "vite": "^3.2.3",
    "vite-plugin-dts": "^1.7.1"
  },
  "dependencies": {
    "isomorphic-fetch": "^3.0.0",
    "url": "^0.11.0"
  }
}

This updated package is being used in two projects that are also based on Vite.

One project runs unit tests using Vitest without any issues, while the other project uses Jest for unit testing and encounters errors like the following for each file importing the package:

Cannot find module '@myRegistry/my-package' from 'src/fileToTest.ts'


Require stack:
  src/fileToTest.ts
  tests/unit/fileToTest.spec.ts

Below is the jest.config.js file of the problematic project:

module.exports = {
  coverageReporters: ['cobertura'],
  moduleDirectories: [
    'node_modules',
    'src'
  ],
  moduleFileExtensions: ['js', 'ts', 'vue'],
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1'
  },
  modulePaths: ['<rootDir>', '<rootDir>/node_modules'],
  preset: 'ts-jest/presets/default-esm',
  rootDir: './',
  setupFilesAfterEnv: ['<rootDir>tests/setup.ts'],
  testEnvironment: 'jest-environment-jsdom',
  testMatch: ['**/tests/unit/**/?(*.)+(spec|test).[jt]s?(x)'],
  transform: {
    '.*\\.(vue)$': '@vue/vue2-jest',
    '^.+\\.(js|jsx)$': 'babel-jest',
    '^.+\\.(ts|tsx)?$': 'ts-jest'
  },
  transformIgnorePatterns: ['/node_modules/']
}

If anyone could provide some insights into what might be missing or causing these issues, I would greatly appreciate it.

Answer №1

The problem arose when we decided to remove CommonJS support from the module I referred to as my-package. By reintroducing CommonJS support, we were able to resolve the issue. Another solution could be switching from jest to vitest.

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

MUI is designed to only manage either onBlur or onKeyPress, but not both simultaneously

Currently, I am working on a project with TypeScript and Material-UI. My main goal is to handle both the onBlur event and the onEnter key press event for a TextField component. Here's the scenario: I have incorporated this text field into a menu. Whe ...

What is the specific significance of the term "next" within package.json dependencies?

Can you explain the significance of using "next" in the package.json dependencies? "dependencies": { "react": "^15.4.2", "react-dom": "^15.4.2", "react-router-dom": "next" } ...

What advantages do binary shifts offer in enums?

What do you think about this code snippet? /** * Bitmask of states */ export const enum ViewState { FirstCheck = 1 << 0, // result is 1 ChecksEnabled = 1 << 1, // result is 2 Errored = 1 << 2, // result is 4 ...

While running tests on a React project, the `npm test` command is successful, but unfortunately,

I created a new react app using create-react-app and included some basic components and tests. The tests work fine when running 'npm test', but I encounter an 'Unexpected token' error when using Jest to run the tests with imported compo ...

Understanding Multiple Type Scenarios in React with Typescript

Code Demonstration: type PropsType = {top: number} | {bottom: number} // The function that moves something in one direction by a specific distance. function move(props: PropsType) { ... } Expected Usage: move({top: 100}) or move({bottom: 100}) Avoid us ...

The comparison between "rxjs-tslint" and "rxjs-tslint-rules" npm packages

Previously, I utilized the rxjs-tslint-rules package to identify RxJS-related issues in my projects. This package was included in the devDependencies section of my projects' package.json files. Now, there is a new rxjs-tslint package that introduces ...

Creating a Typescript interface for a sophisticated response fetched from a REST API

I'm currently struggling with how to manage the response from VSTS API in typescript. Is there a way to handle this interface effectively? export interface Fields { 'System.AreaPath': any; 'System.TeamProject': string; 'Sys ...

create an endless loop to animate in angular2

Is there a way to add iterations, or something similar to the ccs3 animation-iteration-count in Angular 2 animations? I've looked but can't find anything related. How can we apply an infinite play to the animation? Where should we include that o ...

Jest is unable to execute tests containing methods within a .tsx file

Typically, I only test files ending with .ts, but this time I have a file containing utility methods that return a react element. Therefore, my file has a .tsx extension and includes components from material ui and other libraries. Initially, I encountere ...

Creating an Angular form from scratch using HTML

I've developed a component named login. Initially, I created an HTML form called login.component.html and then decided to convert it into an Angular form. To achieve this, I inserted <form #loginform="ngForm"> in the login.component.ht ...

What improvements can I make to enhance my method?

I have a block of code that I'm looking to clean up and streamline for better efficiency. My main goal is to remove the multiple return statements within the method. Any suggestions on how I might refactor this code? Are there any design patterns th ...

Troubleshooting and setting breakpoints in TypeScript code for Angular Web applications using the Firefox browser

Is there a method to add breakpoints to .typescript source files in my Angular application with Firefox Developer Tools? While I am able to add breakpoints to the generated javascript files, is it possible to debug the .ts source files directly? This quer ...

Utilizing Jest to Mock a jQuery Method within a Promise

I have created a function that utilizes a jQuery function named dataFunc, which is expected to return an object. Instead of testing the dataFunc function itself, I want to focus on testing the promise it produces. To achieve this, I need to mock the respo ...

Are there more efficient methods for utilizing local scope when defining a variable?

Having experience in the ML world, I'm used to creating variables with limited scope like this: let myVar = let result1 = doSomething() let result2 = doSomethingElse() result1 + result2 In TypeScript, it seems you can achieve similar sco ...

Jest does not support util.promisify(setTimeout) functionality

While I understand there may be similar questions on SO, I believe mine is unique and hasn't been addressed in the current answers. I'm currently experimenting with testing a REST API in Express.JS. Below, you'll find a basic working exampl ...

Change an array of objects into a map where each object is indexed by a unique key

I'm attempting to transform an array of objects into a map, with the index based on a specific attribute value of the object in typescript 4.1.5 Additionally, I am only interested in attributes of a certain type (in this case, string) A similar ques ...

What is the best way for a function to accommodate various types that adhere to an interface?

How can we create a function that can accept multiple types with a common interface? Let's consider the example: interface A {a: number} type B = {b: string;} & A type C = {c: string;} & A function acceptA(a: A) { return a } acceptA({a ...

Show image using Typescript model in Angular application

In my Angular (v8) project, I have a profile page where I typically display the user's photo using the following method: <img class="profile-user-img" src="./DemoController/GetPhoto?Id={{rec.Id}}" /> However, I am considering an alternative ap ...

Display a JSON file within an Angular application using HTML

I have a JSON (link to the JSON) that I want to display in an html file. JSON: { "recipes": { "FRYING": { "Anchovies": [ [ {"500": "thawing"} ], [ {"60": "nothing"} ] ], "Codfis ...

How does Typescript's dynamic tuple typing tool display all available options in Autocompletion/Intellisense?

Being new to TypeScript, I am facing an issue that I am unsure how to resolve. I want to generate a list of tuples from a list of components. Each tuple should consist of the component's name (keyof MyComponents) and its attributes. (Refer to the co ...