`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

Angular makes it easy to extract multiple parameters from a URL

In the process of developing a basic Angular application using TypeScript, I have encountered an issue. Within my project, there is a URL structure like this: www.example.com/api/1/countries/Italy/ My goal is to extract the values 1 and Italy from this U ...

Combining two observables into one and returning it may cause Angular guards to malfunction

There are two important services in my Angular 11 project. One is the admin service, which checks if a user is an admin, and the other is a service responsible for fetching CVs to determine if a user has already created one. The main goal is to restrict ac ...

Creating an array that exclusively contains numbers using anonymous object export: A step-by-step guide

I am struggling with a record that is designed to only accept values of type number[] or numbers. This is how it is structured: type numberRecords = Record<string,number[]|number>; I ran into an error when trying this: export const myList:numberRec ...

The absence of a semicolon following the interface declaration is the issue

I am facing a slight issue with ESLint and Typescript, particularly regarding semicolons after declaring interfaces. Additionally, I utilize VSCode as my editor with automatic formatting upon saving. Below is the configuration in my .eslintrc.json file: ...

Using function overloading in TypeScript causes an error

I'm currently exploring the concept of function overloading in TypeScript and how it functions. type CreateElement = { (tag: 'a'): HTMLAnchorElement (tag: 'canvas'): HTMLCanvasElement (tag: 'table'): HTMLTableElem ...

Image paths becoming unresponsive following package upgrades

My Angular2 application was originally built using angular-cli (v 1.0.0) and webpack2. Within a component, I had the ability to reference an image like so: <div class="country-flag"> <img [src]="src/assets/flags/32/jp.png" [width]="flagIconSiz ...

What is the method for adjusting the spacing between binding tags within HTML code formatting specifically for TypeScript elements in IntelliJ?

My Angular binding currently defaults to <h1>{{typeScriptVar}}</h1>, but I would like it to be set as <h1>{{ typeScriptVar }}</h1> when I use the format code shortcut in InteliJ. Can anyone assist me with this issue? I have resear ...

Contrasting expressEngine and ng2engine: An In-depth Comparison

I am currently utilizing the universal-starter framework. In regards to the file server.ts, I noticed that making the switch from import { expressEngine } from 'angular2-universal'; app.engine('.html', expressEngine); to import { n ...

Anticipate a nested attribute within a templated function parameter that is determined by the type of the template

My goal is to ensure that the "options" property of the parameter object includes the "label" property. I attempted to achieve this, but encountered compilation errors in my code. interface BaseOptionType { label: string; } interface CreatableAutoComp ...

While running tslint in an angular unit test, an error was encountered stating 'unused expression, expected an assignment or function call'

Is there a method to resolve this issue without needing to insert an ignore directive in the file? Error encountered during command execution: ./node_modules/tslint/bin/tslint -p src/tsconfig.json --type-check src/app/app.component.spec.ts [21, 5]: unuse ...

Exploring Local Gems with Google Places API in Ionic 2

I recently integrated the Google Maps API into my app and now I am looking to incorporate Google Places as well. I have managed to successfully implement Geolocation, but I am facing difficulties when trying to perform a nearby search for "supermarkets" in ...

Using ESLint to enforce snake_case naming conventions within TypeScript Type properties

When working with TypeScript, I prefer to use snake_case for properties within my Interfaces or Types. To enforce this rule, I have configured the ESLint rule camelcase as follows: 'camelcase': ["error", {properties: "never"}], Even though the E ...

Fetching an item from Local Storage in Angular 8

In my local storage, I have some data stored in a unique format. When I try to retrieve the data using localStorage.getItem('id');, it returns undefined. The issue lies in the way the data is stored within localStorage - it's structured as a ...

Could it be possible for a Firestore onUpdate trigger's change parameter, specifically change.after.data() and change.before.data(), to become null or undefined?

Presented below is a snippet of my cloud function exports.onUpdateEvent = functions.firestore.document('collection/{documentId}') .onUpdate((change, context) => { const after: FirebaseFirestore.DocumentData = change.after.data(); const ...

The attribute 'use' is not found within the data type 'typeof...', and the property 'extend' is not present within the data type 'typeof'

As I embark on building my very first Vue app using TypeScript, I find myself facing a frustrating issue: Property 'xxx' does not exist on type 'typeof. Despite my efforts to research similar problems, none of the suggested solutions have pr ...

Tips on managing individual Firebase accounts for multiple Node.js projects

Recently, I have been utilizing npm firebase-tools to deploy my nodejs web applications. However, I have encountered an issue with managing multiple projects. Whenever I log in to a Firebase account, it automatically logs me in for all of my projects. Th ...

What is the proper way to mention JavaScript packages when including them as parameters in Angular elements within HTML?

I was looking to enhance the command to be more authoritative. <div (click)="lastCall(999)">click me</div> My attempt to utilize Number.MAX_SAFE_INTEGER resulted in an error from my computer stating that it wasn't recognized. As a result ...

What steps can be taken to resolve the error message "Using 'null' as an index type is not allowed."?

In my TypeScript code, I have a variable called lang declared as a string type value, and a variable called direction declared as an object with two elements. I also have a function that is supposed to return the value of the direction object based on th ...

Typescript defines types for parameters used in callbacks for an event bus

Encountering a TypeScript error with our custom event bus: TS2345: Argument of type 'unknown' is not assignable to parameter of type 'AccountInfo | undefined'. Type 'unknown The event bus utilizes unknown[] as an argument for ca ...

Dynamic React Gallery with Interactive Image Picker

Looking to develop a new photo management application as an alternative to Google Photos, with a focus on displaying and selecting images in a user-friendly way. Currently using the react-grid-gallery library for this purpose. Here is my current implement ...