What could be the reason for mocha failing to function properly in a project that is set up

During a unit test in my TypeScript project using mocha, I encountered an issue when setting the project type to module. The error message displayed is as follows:

➜  typescript-project yarn test
yarn run v1.22.17
warning package.json: No license field
$ mocha --require ts-node/register test/**/**

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /Users/xiaoqiangjiang/source/reddwarf/demo/typescript-project/test/stack.ts
    at new NodeError (node:internal/errors:371:5)
    at Object.file: (node:internal/modules/esm/get_format:72:15)
    ...

To replicate this issue, I created a minimal project structure. Below is the package.json configuration of the TypeScript project:

{
  "type": "module",
  "devDependencies": {
    "@types/chai": "^4.3.0",
    "@types/mocha": "^9.1.0",
    ...
  },
  "scripts": {
    "test": "mocha --require ts-node/register test/**/**"
  }
}

The test file content is as follows:

import { expect } from 'chai';

describe('Stack', () => {
    it('can be initialized without an initializer', () => {
        
    });
    
});

Furthermore, here is the tsconfig.json configuration used in the project:

{
  "compilerOptions": {
    "esModuleInterop": true,
    ...
  }
}

Upon running the yarn test command, the error persists. However, removing the

"type": "module",
line resolves the issue. It seems that mocha does not fully support projects with a module type. Is there a way to make mocha work seamlessly with a module-based project structure?

Answer №1

To switch to ESM module loader for modules in your project, update the test script as follows:

-    "test": "mocha --require ts-node/register test/**/**"
+    "test": "mocha --loader ts-node/esm test/**/**"

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

In React + TypeScript, learn how to effectively pass down a function from a container component to a

I am currently working on developing a tabs application using React and Typescript. The main component, Tabs, manages the state and passes it down to the Content component. Additionally, I have implemented a function called 'handleName' which is ...

Can you explain the distinction between Reflect.getMetadata and Reflect.getOwnMetadata?

Just like the title says, the reflect-metadata API comes with a method called getMetadata and another called getOwnMetadata. Can you explain the distinction between them? The same question applies to hasOwnMetadata, and so on. ...

What does Typescript compile when aiming for ES5 / ES3?

I'm currently grappling with the nuances of when the Typescript compiler decides to transpile code in order to align it with my designated target ECMAScript version (ES5 or ES3). As an example, TSC has no problem transpiling for(var int of intArray); ...

Update each number in an array by appending a string within a table in an Angular component, rather than the

I have created a function that decides on a comment based on the result number added to an array and displays it in a table. However, calling this function within the template is causing a performance slowdown. Is there a way to achieve the same outcome w ...

Replacing the '+' character with a space in HttpParams within Angular 6

When passing a JSON object using HttpParams, the + character is automatically converted to a space before being sent to the backend. Despite trying multiple solutions, I have been unable to resolve this issue for a JSONObject string. this.updateUser({"nam ...

Mastering the Conversion from NGRX Effect to NGRX Effect v15

I am currently working on converting the code snippet to NGRX 15. As a newcomer to Angular, I could use some guidance. "@ngrx/effects": "^15.4.0" @Injectable() export class SnackbarEffects { @Effect({ dispatch: false }) cl ...

The function is not operational while executing addEventListener

I'm encountering some bugs in my Angular 1.5 project with TypeScript. I'm trying to retrieve the scrollTop value from the .uc-card element. public container = document.querySelector(".uc-card"); In my $onInit, I have: public $onInit() { this ...

Angular firebase Error: The parameter 'result' is missing a specified type and is implicitly assigned the 'any' type

I have encountered an issue with the code I am working on and both the result and error are throwing errors: ERROR in src/app/login/phone/phone.component.ts(48,75): error TS7006: Parameter 'result' implicitly has an 'any' type. s ...

I'm trying to figure out how to access the array field of an object in TypeScript. It seems like the type 'unknown' is required to have a '[Symbol.iterator]()' method that returns an iterator

I'm currently tackling an issue with my helper function that updates a form field based on the fieldname. For example, if it's the name field, then form.name will be updated. If it's user[0].name, then the name at index 0 of form.users will ...

My router-outlet is malfunctioning when trying to display my component

I am currently diving into learning Angular 2 in order to revamp my personal website. However, I've encountered an issue where my application fails to load the component when I navigate to the appropriate route by clicking on the navigation bar. Insi ...

When using @testing-library/react (rtl), the 'waitFor' function achieves success even without the need for the 'await' keyword

waitFor() is causing my test to fail while waitFor() (without await) makes it pass. The official documentation states: Async methods return a Promise, so you must always use await or .then(done) when calling them. (https://testing-library.com/docs/guide ...

Tips for integrating Excel files with NestJS

I'm in the process of developing a REST API that will utilize a third-party API to retrieve specific status information. The URLs needed for this API are stored in an Excel file, which is a requirement for this use case. My goal is to extract the URLs ...

Executing functions in Vue TypeScript during initialization, creation, or mounting stages

Just a few hours ago, I kicked off my Vue TypeScript project. I've successfully configured eslint and tslint rules to format the code as desired, which has left me quite pleased. Now, I'm curious about how to utilize the created/mounted lifecycl ...

Having trouble directing my attention towards a Mat card when using viewchildren in Angular

My current challenge is trying to focus on a specific card from a list of mat cards Despite my efforts, I keep encountering an error that reads: Cannot read property 'focus' of undefined Access the code on StackBlitz The desired functionali ...

The issue arises due to conflicting indent configurations between eslint and @typescript-eslint/indent

Currently, I am using eslint and prettier in a TS express application. I am trying to set the tab width to 4, but it appears that there is a conflict between the base eslint configuration and the typescript eslint. When looking at the same line, this is w ...

Working with TypeScript: Overriding a Parent Constructor

I am new to TypeScript and currently learning about Classes. I have a question regarding extending parent classes: When we use the extends keyword to inherit from a parent class, we are required to call the super() method in the child class constructor. H ...

Scroll automatically to the last div whenever a button is clicked using React and Typescript

I'm currently working on an application being developed in React + Typescript. I am trying to implement auto-scroll functionality to the last div within a parent div where child divs are dynamically added based on data from an array of objects. The da ...

Error message in Vue3 with TypeScript: When using global components, you may encounter the error "JSX element type '___' does not have any construct or call signatures.ts(2604)."

Each globally registered component suddenly displays a red TypeScript squiggle in the markup! Surprisingly, the app continues to function without any visible errors! This issue arises with all components, whether they are custom-made or third-party libr ...

Exploring Recursive Types in TypeScript

I'm looking to define a type that can hold either a string or an object containing a string or another object... To achieve this, I came up with the following type definition: type TranslationObject = { [key: string]: string | TranslationObject }; H ...

Error message: When using Vue CLI in conjunction with Axios, a TypeError occurs stating that XX

I recently started working with Vue.js and wanted to set up a Vue CLI project with Axios for handling HTTP requests. I came across this helpful guide which provided a good starting point, especially since I plan on creating a large project that can be reus ...