Configuring Jest for Typescript with Module Resolution

The current project utilizes ReactJS, Typescript, Webpack, and Jest. To optimize import and achieve module resolution, certain configurations were adjusted:

TSConfig.js:

"compilerOptions": { "baseUrl": "src",}

Webpack.config.js

alias: {
  Common: path.resolve(__dirname, 'src/Common/'),
},

Although the code is functioning as expected, Jest tests have started failing with the following error:

Cannot find module 'Common/js/utils' from 'MyContact.ts'

This issue arises because Jest is not able to resolve Common to Src/common and is looking in node_module. To resolve this, the following adjustments were made:

jestConfig.js

moduleNameMapper: {"Common": "<rootDir>/src/Common"}

This fix seems to have resolved the previous issue, but now a new problem has surfaced:

Jest encountered an unexpected token

This error typically occurs when Jest is unable to parse a file, indicating that it is not plain JavaScript.

By default, Jest uses a Babel config to transform files, excluding "node_modules".

You can address this issue by:
 • Specifying a custom "transformIgnorePatterns" in your config to have some "node_modules" files transformed.
 • Defining a "transform" option in your config for custom transformation.
 • Stubbing out non-JS modules by using the "moduleNameMapper" config option for mocking.

For more details and examples of these config options, refer to the documentation:
https://jestjs.io/docs/en/configuration.html

Details:

C:\Users\ua\Project\develop\src\Common\index.ts:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export * from './Acc'
                                                                                         ^^^^^^

SyntaxError: Unexpected token export

  at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
  at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)

Below is the full jest.config.js file:

module.exports = {
  verbose: false,
  roots: ["<rootDir>/src"],
  transform: {
    "^.+\\.tsx?$": "ts-jest",
  },
  globals: {
    'ts-jest': {
      diagnostics: false
    }
  },
  moduleNameMapper: {
    "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
      "<rootDir>/__mocks__/fileMock.js",
    "\\.(css|less|pcss)$": "<rootDir>/__mocks__/styleMock.js",
    "Common": "<rootDir>/src/Common",
  },
  snapshotSerializers: ["enzyme-to-json/serializer"],
  setupFilesAfterEnv: ["<rootDir>/setupEnzyme.ts"],
  testMatch: [ "**/__tests__/**/*.test.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)"],
  collectCoverageFrom: ["**/*.{ts,tsx}", "!**/node_modules/**", "!**/vendor/**"]
};

tsconfig.js:

 {
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "src",
    "typeRoots": [
      "./node_modules/@types",
      "./custom_typings"
    ],
    "outDir": "build",
    "module": "commonjs",
    "skipLibCheck": true,
    "moduleResolution": "node",
    "removeComments": true,
    "target": "es5",
    "sourceMap": true,
    "lib": [ "dom", "es2015", "es2017", "esnext" ],
    "noEmit": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "noImplicitAny": false,
    "allowUnusedLabels": false,
    "jsx": "react",
    "allowJs": true,
    "isolatedModules": false,
    "strictNullChecks": false,
    "noEmitHelpers": false,
    "allowSyntheticDefaultImports": true
  },
  "typeRoots": [
    "./node_modules/@types",
    "./custom_typings"
  ],
  "exclude":[
    "./node_modules"
  ],
  "include": [
    "src/*",
    "custom_typings"
  ]
}

Answer №1

Great news! I managed to resolve the module issue by including the following line in jest.config.js

moduleDirectories: ["node_modules", "src"],

Answer №2

It appears that babel does not support parsing typescript test files by default. To remedy this, please execute

npm install ts-jest babel-jest --save-dev
Following that, add the following configuration to your jest.config.js file.

  transform: {
    '^.+\\.jsx?$': require.resolve('babel-jest'),
    '^.+\\.tsx?$': 'ts-jest',
  }

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

Error TS2339: Property does not exist on type 'object' - Typescript arrow function issue

In my experience with Angular, I have noticed that I encounter typescript compile errors quite often when using fat arrow functions within an rxjs stream. Despite being able to run the app and having it transpile successfully, I am curious about how to re ...

Please input the number backwards into the designated text field

In my react-native application, I have a TextInput where I need to enter numbers in a specific order such as 0.00 => 0.01 => 0.12 => 1.23 => 12.34 => 123.45 and so on with each text change. I tried using CSS Direction "rtl" but it didn' ...

Alerts in Angular templates of inherited class in WebStorm

While working with WebStorm 2019.3.2, I have noticed some warnings in Angular templates: https://example.com/image.png This is happening because the properties are being initialized on the parent component instead of the child. @Component({ selector: ...

Is there a way in Jest to restrict function calls to only those that are expected and disallow any other unauthorized calls

When working with Jest, you have the ability to mock out and spy on function calls within a function using functionalities like jest.spyOn and jest.fn() with .toHaveBeenCalledTimes(1) etc. However, in Spock framework testing, you can conclude your unit tes ...

Leverage both props and destructuring in your Typescript + React projects for maximum efficiency!

Is it possible to use both destructuring and props in React? For instance, can I have specific inputs like name and age that are directly accessed through destructuring, while also accessing additional inputs via props? Example The desired outcome would ...

Developing a TypeScript frontend library

I am currently in the process of creating a frontend library consisting of React components and CSS/SCSS. Specifically, I am looking for: To build a single CommonJS .js file and .css file. To exclude external libraries (e.g. React) from the .js output. ...

The array remains undefined even after being assigned within the subscribe function

I have encountered an issue in my Angular app where the array productLocations is being assigned in the ngOnInit method within a subscription, but it remains undefined when used in another method. Despite following advice on Stackoverflow to move the assig ...

Storing TypeScript functions as object properties within Angular 6

I am working on creating a simplified abstraction using Google charts. I have implemented a chartservice that will act as the abstraction layer, providing options and data-source while handling the rest (data retrieved from a REST API). Below is the exist ...

Is it possible to nullify an object and utilize nullish coalescing for handling potentially undefined constants?

In my development work with React, I often utilize a props object structured like this: const props: { id: number, name?: string} = { id: 1 }; // 'name' property not defined const { id, name } = props; // the 'name' constant is now fore ...

Updating Angular model remotely without relying solely on the controller

I am struggling to call the addRectangleMethod method from my Javascript code in order to retrieve server-side information into the Angular datamodel. However, I keep encountering an error stating that the method I'm trying to call is undefined. It&ap ...

I am trying to replace the buttons with a dropdown menu for changing graphs, but unfortunately my function does not seem to work with the <select> element. It works perfectly fine with buttons though

I am currently working on my html and ts code, aiming to implement a dropdown feature for switching between different graphs via the chartType function. The issue I am facing is that an error keeps popping up stating that chartType is not recognized as a ...

Bringing in a module that enhances a class

While scouring for a method to rotate markers using leaflet.js, I stumbled upon the module leaflet-rotatedmarker. After installing it via npm, I find myself at a loss on how to actually implement it. According to the readme, it simply extends the existing ...

What is the benefit of utilizing ngSubmit over just using a basic button and function?

Lately, I've been pondering whether to utilize ngSubmit or simply bind a (click)="submit()" on a button. There's been much debate about using submit and ngSubmit, but is it necessary to rely on the traditional HTML submit method? Particularly wh ...

Determining When to Activate Button Based on Angular - Verifying That All Choices Have Been Ch

This quiz application requires the user to choose options before proceeding to the next page, with the next button being disabled by default. Once all options are chosen, the next button should become enabled. NOTE: Although the functionality for selecti ...

Displaying object properties in React and rendering them on the user interface

Within my React application, I am retrieving data from an API using the following code snippet: function PlayerPage() { interface PlayerDataType { id: number; handle: string; role: string; avatar: string; specialAbilities: null; s ...

Having trouble with TypeScript error in React with Material-UI when trying to set up tabs?

I have developed my own custom accordion component hook, but I am encountering the following error export default const Tabs: OverridableComponent<TabsTypeMap<{}, ExtendButtonBase<ButtonBaseTypeMap<{}, "button">>>> Check ...

Pass on only the necessary attributes to the component

I have a simple component that I want to include most, if not all, of the default HTML element props. My idea was to possibly extend React.HTMLAttributes<HTMLElement> and then spread them in the component's attributes. However, the props' ...

`How can TypeScript scripts be incorporated with Electron?`

As I work on my simple electron app, I am facing an issue where I need to include a script using the following code: <script src="build/script.js"></script> In my project, I have a script.ts file that compiles to the build folder. im ...

Unlocking new perspectives with a click

Currently exploring Angular development, I have encountered a question here but couldn't find the solution I was looking for. I am seeking suggestions and ideas on how to approach this issue. Essentially, my HTML includes buttons like the ones shown ...

fakeAsync failing to synchronize with async task completion

Scenario In my testing process, I am evaluating a component that utilizes an observable-based service to retrieve and display data for internationalization purposes. The i18n service is custom-made to cater to specific requirements. While the component ...