A guide to setting up Jest for testing a TypeScript/ExpressJS application with typeRoots enabled in the tsconfig.json file

Hey there, I'm currently working on a project which includes TypeScript and Express.js. Right now, my main focus is on setting up the tests. However, when I try to run yarn test (which essentially runs jest without any additional flags), I encounter this specific error:

PS C:\Users\joaov\Documents\gittin> yarn test
yarn run v1.22.10
$ jest
Error: Jest: Failed to parse the TypeScript config file C:\Users\joaov\Documents\gittin\jest.config.ts
  TSError: ⨯ Unable to compile TypeScript:
jest.config.ts:1:1 - error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.

1 module.exports = {
  ~~~~~~

    at readConfigFileAndSetRootDir (C:\Users\joaov\Documents\gittin\node_modules\jest-config\build\readConfigFileAndSetRootDir.js:118:13)
    at readConfig (C:\Users\joaov\Documents\gittin\node_modules\jest-config\build\index.js:227:18)
    at readConfigs (C:\Users\joaov\Documents\gittin\node_modules\jest-config\build\index.js:412:26)
    at runCLI (C:\Users\joaov\Documents\gittin\node_modules\@jest\core\build\cli\index.js:220:59)
    at Object.run (C:\Users\joaov\Documents\gittin\node_modules\jest-cli\build\cli\index.js:163:37)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I've been informed that the reason behind this error is the inclusion of the property typeRoots in my tsconfig.json. By commenting out that line, the tests do work as intended, but I am curious to find out how I can make the typeRoots functionality compatible with jest in order to retain that necessary local type.

To expedite things, here are the contents of my tsconfig.json and jest.config.ts files respectively:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "outDir": "dist",
    "rootDir": "src",
    "removeComments": true,
    "strict": true,
    "strictPropertyInitialization": false,
    "typeRoots": ["./src/@types"],
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "exclude": [
    "src/**/*.spec.ts",
    "src/**/*.test.ts",
    "jest.config.ts",
    "ormconfig.js",
    "node_modules"
  ]
}
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
};

Answer №1

discovered that the solution was as simple as including ./node_modules/@types in the typeRoots configuration option of the tsconfig file.

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

Filtering tables with checkboxes using Next.js and TypeScript

I've recently delved into Typescript and encountered a roadblock. While I successfully tackled the issue in JavaScript, transitioning to Typescript has left me feeling lost. My dilemma revolves around fetching data from an API and populating a table u ...

A guide on incorporating a JavaScript plugin using Vue.use() into a TypeScript project equipped with typings

Currently, I am facing an issue while attempting to integrate Semantic-UI-Vue into my Vue project. Upon trying to execute Vue.use(SuiVue), the following error message is displayed: Argument of type 'typeof import("semantic-ui-vue")' is not ass ...

Production environment sees req.cookies NEXTJS Middleware as undefined

Here is my latest middleware implementation: export async function middleware(request: NextRequest) { const token = request.headers.get('token') console.log(token) if (!token || token == undefined) { return NextResponse.redirect(new URL('/lo ...

Unable to retrieve values using any = {} in TypeScript Angular 8

import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { enableProdMode } from '@angular/core'; enableProdMode(); @Component({ selector: 'app-home', templat ...

Encountering the error "Cannot read property 'header' of undefined" while conducting tests on Nodejs using supertest

In my server.js file, I have set up my express app. I tried to run a demo test in my test file using express, but unfortunately, the test did not run successfully. const request = require('supertest'); const express = require('express' ...

Retrieve the child component's HTML element within the parent component

attendees.component.html (Parent) <app-add-guest (guestUserChange)="addGuest($event)"></app-add-guest> add-guest.component.html (Child) <form [formGroup]="form"> <ion-row> <ion-col> <ion-it ...

Is there a distinction between Entity[] and array<Entity> in TypeScript?

Everything in the title, for example people: Person[]; people: Array<Person>; What sets them apart? Is there a preferred approach? Note: I couldn't find any guidance on this and I've encountered both in code. ...

Problem with opening the keyboard feature in an Ionic app

Hello everyone, I'm relatively new to Ionic development and I've been trying to integrate a keyboard plugin into my application that opens from the footer and focuses on input fields for entering values. Here is the link to the plugin I used: ht ...

Get data from an Angular 12 hyperlink

Here is the link to my questionnaire: http://localhost:4200/EditQuestionnaire;id=1;name=Random%20Questionnaire I have included this code in the ngOnInit() function, however, I am having trouble retrieving the values: ngOnInit(): void { this.ro ...

Using React, TypeScript, and Next.js to transform all elements in a static array to their last occurrence

I'm having trouble updating my array. Every time I click the button for the second time, only two or more records are added, similar to the last one I added. Does anyone know how to fix this issue? In the images below, you can see the results of the ...

Having difficulty grasping the significance of the data received from the API response

Currently, as I am working on my personal Portfolio for a Web Developer course, I have encountered an issue with correctly implementing my API to retrieve information from the database. Previously, I faced no problem when using a .json file, but now, I am ...

The issue of updating a GLSL uniform variable during an animation in three.js using TypeScript remains unresolved

Running a three.js TypeScript application, I developed custom GLSL shaders using the THREE.ShaderMaterial() class. Now, I aim to enhance my code by switching to the THREE.MeshStandardMaterial class. This is an entirely new experience for me, and despite e ...

Defining the type of a React component class constructor in TypeScript that includes a specific static method

After successfully implementing regular classes, including subclasses, with TypeScript, I encountered an issue when working with React components. The explanation provided by TypeScript was limited. import React from 'react' type Props = { tes ...

Trouble with launching Jasmine tests within define block in compiled Typescript

Currently, I am immersed in a testing project that involves setting up a pure Javascript Jasmine Karma environment to test a pre-compiled Typescript setup. Despite my efforts, I am facing an issue where the test cases refuse to start running. While the co ...

Currently using Mongoose and Luxon to showcase the event date, however, I am encountering an issue where the displayed date is one day earlier than expected

Currently, I am working with Mongoose and Luxon to present a date chosen by the user from a form. However, there seems to be an issue where the date is being console logged as one day, but appearing on the page as the previous day. Below is my model setup ...

Executing axios calls within other axios calls and altering state in React before all calls have completed

Currently, I am working on implementing nested axios calls to create the desired object by making multiple API requests. However, I am facing an issue where the state updates before all requests have finished, causing my table to populate entry by entry ...

TS: A shared function for objects sharing a consistent structure but with varied potential values for a specific property

In our application, we have implemented an app that consists of multiple resources such as Product, Cart, and Whatever. Each resource allows users to create activities through endpoints that have the same structure regardless of the specific resource being ...

Using JQuery to test for element visibility in Jest tests

I am currently facing an issue in my unit test where the visibility state of an element does not change as expected. I am using .is(":visible") to verify this, and while it works fine in browsers, the unit test always reports that the element is hidden. B ...

A guide to sending HTTP requests using TypeScript

Is it possible to make API calls from TypeScript and use "async-await" with it? I am currently in the process of converting React code to TypeScript. Currently utilizing Axios for making HTTP Requests ...

Issue with Build System CTA's/Callback function functionality not operational

I have encountered an issue with my build/design system. Although everything works fine during development, when I publish my package and try to use the callback function, it does not return the necessary data for me to proceed to the next screen. I tried ...