`Troubleshooting problem with debugging mocha tests in a TypeScript environment`

I'm currently facing an issue while trying to debug a mocha test. Despite my efforts in searching on Google and Stack Overflow, I have not been able to find a solution.

The error message is as follows:

TSError: ⨯ Unable to compile TypeScript:
source-map-support.js:444 error TS2468: Cannot find global value 'Promise'.backend/test/textToSpeech/lib.ts(11,30): error TS2705: An async 
function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option.backend/test/textToSpeech/lib.ts(12,27): error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option.

This is how the tsconfig.json file is configured:

{
"compilerOptions": {
  "module": "commonjs",
  "watch": true,
  "noImplicitAny": false,
  "removeComments": true,
  "outDir": "./dist",
  "sourceMap": true,
  "target": "es6",
  "lib": [
      "ES2015"
  ],
  "types": [
    "node",
    "pg-promise"
  ],
  "typeRoots": [
    "node_modules/@types"
  ]
  },
  "include": [
  "src/**/*"
 ],
"exclude": [
  "node_modules",
  "**/*.spec.ts"
 ]
}

As for the vscode launch.json configuration:

{
      "type": "node",
      "request": "launch",
      "name": "Mocha Tests",
      "program": "${workspaceFolder}/backend/node_modules/mocha/bin/_mocha",
      "args": [
          "--require", "ts-node/register",
          "-u",
          "tdd",
          "--timeout",
          "999999",
          "--colors",
          "${workspaceFolder}/backend/test/textToSpeech/lib.ts"
      ],
      "internalConsoleOptions": "openOnSessionStart"
  }

The contents of the test file are as follows:

import {} from 'mocha'
import { expect } from 'chai'
import config from '../configuration'
import { TextToSpeechLib } from '../../src/libs/textToSpeech/'
var textToSpeach = new TextToSpeechLib(config)

var text = 'Hello world'


describe('TextToSpeach lib', async () => {
  it ('Convert text ...', async () => {
    console.log("==== =a= =s= a==")
    let resp = await textToSpeach.convertText(text);
    expect(resp.status).to.be.equal('success')
  })
})

I've tried various solutions but it seems like the launcher is not loading the tsconfig. I even attempted to pass "--lib","'ES2015'" as an argument in the launcher configuration. Any help would be greatly appreciated. Thank you.

Answer №1

Update: It's important to note that this answer may be outdated, and there could be more effective solutions available now to resolve the issue at hand. I have not verified this method recently.

The error message provides clear instructions on what steps to take:

Ensure you have a declaration for the 'Promise' constructor or include 'ES2015' in your --lib option

As we shouldn't define our own specifications, it is recommended to add 'ES2015' to the options.

How can you accomplish this?

Navigating through all the ts-node setup details can be complex. Someone with expertise in this area might know how to specify a particular tsconfig file, but I am unable to provide that guidance. Instead, setting an environment variable seems like a viable approach.

After examining the source code, I discovered that the essential env var is TS_NODE_COMPILER_OPTIONS. Thus, when invoking ts-node, the process.env needs to contain the attribute:

TS_NODE_COMPILER_OPTIONS={"lib": ["ES2015"], ...}

What are the steps to achieve this?

If you are using VS Code for debugging, you can configure it by adding the following:

"env": {"TS_NODE_COMPILER_OPTIONS":"{\"lib\": [\"ES2015\"]}"}

For running tests, such as with npm test, you can include this option in the environment variables before executing the test script with cross-env.

In my package.json, I added something similar to the following:

"scripts": {
    "test": "cross-env TS_NODE_COMPILER_OPTIONS=\"{\\\"lib\\\": [\\\"ES2015\\\"]}\" mocha --require ts-node/register path/to/test(s).ts"
}

Note - The triple backslashes are intentional

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

Extracting PNG file from response (bypassing standard JSON extraction)

Despite my efforts to find a solution, I am still unable to resolve this specific issue: I have implemented an Angular request (localhost:4200) to an API on Spring (localhost:8080). The HttpService successfully handles the requests, except when it comes to ...

Struggling with TypeScript Errors while Extending Theme Colors in Material UI React using TypeScript

Just started with typescript and feeling a bit lost, can someone offer some guidance? I'm working on a React project using material-ui with typescript. To add a new color the correct way, it needs to be added to a theme: const theme = createMuiTheme({ ...

Facing problem with Angular 7 when making a GET request for non-JSON data

Currently, I am retrieving JSON data from a URL using the following method: this.http.get('http://localhost:3200/mydata').subscribe(data => { console.log(data); }); The response is in JSON format, and everything seems to be working fine. ...

Ways to incorporate suspense with NextJS 14 - how can I do it?

I am looking to add a suspense effect to the initial loading of my page while the assets are being fetched. These assets include images on the home screen or as children of the RootLayout component. How can I implement an initial Loading state for these ...

Issues encountered with Nextjs 13.4 and Next-Auth 4.2 regarding the signIn("credentials", { }); functionality not functioning as expected

When using next-auth credentials in my current project, I encountered an issue with the signIn() function from next-auth/react. It appears that the redirection to the admin page persists regardless of whether the login details are correct or not. {error: n ...

Tips for specifying the type when utilizing the spread operator to pass props

type TypeData = { data: { id: string; class: string; name: string; country: string; ew_get_url: string; ew_post_url: string; rocket_id: string; pages: { landing: { h1: string; h2: string; } ...

incorporating my unique typographic styles into the MUI framework

I'm currently working on customizing the typography for my TypeScript Next.js project. Unfortunately, I am facing difficulties in configuring my code properly, which is causing it to not work as expected. Can someone kindly provide assistance or guida ...

An exception is thrown by TypeScript's readline.createInterface function

My current project involves creating an electron app. I am facing an issue in the main.ts file where I have constructed a seemingly simple class with a constructor that is not running as expected. The problem arises when the call to readline.createInterfac ...

The Observer<T> generic type necessitates the specification of 1 type argument

I'm currently trying to grasp the concept of Observables in Angular 4. While watching a tutorial video on it, I attempted to create my first Observable but encountered an error in my IDE: The generic type Observer requires 1 types argument(s) Here ...

Collaborate and apply coding principles across both Android and web platforms

Currently, I am developing a web version for my Android app. Within the app, there are numerous utility files such as a class that formats strings in a specific manner. I am wondering if there is a way to write this functionality once and use it on both ...

Caution: Unable to load bindings, resorting to pure JS instead (consider running npm run rebuild?) within AWS SAM

When I run a sam local invoke to call a typescript AWS Lambda function locally, I am encountering a warning: 2023-04-04T08:53:29.931Z undefined WARN bigint: Failed to load bindings, pure JS will be used (try npm run rebuild?) Should I conf ...

Exploring the process for transitioning between pages within Angular

I am working on an Angular project and I am looking to navigate to the registration page when the registration button is clicked. As a beginner, I attempted to link the registration page but encountered some issues. My goal is for the main page to disappea ...

Oops! Make sure to explicitly allow the dependency @types/html2canvas by adding it to the "allowedNonPeerDependencies" option

After installing the html2canvas package in my Angular library project, I encountered an error when compiling in production mode using the command ng build --prod. The specific error message is as follows: ERROR: Dependency @types/html2canvas must be exp ...

Angular 2: Shared functions for universal component usage

I am working on an Angular 2 webpack project and I have come across a scenario where I have some functions that are repeated in multiple components. I want to find a way to centralize these functions in a "master" class or component so that they can be eas ...

Changing the color of a Chart.js chart in Angular: A step-by-step guide

I've been struggling to change the color of my chart without success. Any assistance on this matter would be greatly appreciated. Despite trying to assign color values to datasets, I am still unable to achieve the desired result. This is a snippet f ...

Utilizing Dynamic Class Names in Angular 7 with Typescript

In the process of developing an Angular 7 application, I have created a form component that is intended to be used for various entities. As part of this, I defined a variable route: {path: ':entity/create', component: FormComponent} While this ...

Issue with NgModule in Angular application build

I'm facing an issue with my Angular application where the compiler is throwing errors during the build process. Here's a snippet of the error messages I'm encountering: ERROR in src/app/list-items/list-items.component.ts:9:14 - error NG6002 ...

The panning functionality on Android devices within the Firefox browser is currently experiencing issues with both panstart and pan

Currently, I am collaborating on an Angular7 project and utilizing hammerjs version 2.0.1. One of the tasks at hand is to allow panning functionality on a map for mobile devices. After testing on various android devices, I noticed that it performs well on ...

What is the best way to send key combinations to a Selenium ChromeDriver?

While using uirecorder to create mocha test cases for testing my web program, I encountered an issue with sending key combinations such as "Metakey + R". Despite being able to easily send single keys like '{DOWN}', figuring out how to send key co ...

What steps should I take to resolve the 'invalid mime type' issue while transmitting an image as a binary string to Stability AI via Express?

Currently, I am facing an issue while attempting to utilize the image-to-image API provided by stabilityAI. The task at hand involves sending an image as a binary string through my express server to the stability AI API. However, when I make the POST reque ...