Merge mocha with Typescript, and include the watch feature

For my project, I have set up mocha to test my Typescript code. The issue arises when running the command:

mocha ts/test --compilers ts:typescript-require

Every time I make a change, it fails with an error message like this:

error TS2307: Cannot find module 'mocha'.

Oddly enough, if I simply run tsc, everything works fine (I have all the necessary type definitions and a tsconfig.json file). I even installed typescript-require for mocha.

What's even more confusing is that after I run the command once, it starts working as expected. However, when I use the watch mode with mocha:

mocha -w ts/test --compilers ts:typescript-require

It initially works but then fails upon subsequent runs. It's frustrating! Does anyone have any tips on setting up a stable configuration for testing and watching Typescript code with mocha?

Answer №1

After encountering a similar need, I created ts-node (https://github.com/TypeStrong/ts-node). My requirement was to execute tests using different test runners and compiling to a separate directory wasn't sufficient as I also prefer embedding the test fixtures. This has evolved into a fully-featured node runtime for TypeScript, complete with a CLI that includes a neat little .type command feature. A README example demonstrates its usage with Mocha.

Currently, it operates entirely in memory, but there are plans to enhance it with additional flags to optimize its suitability for production environments (such as minimal runtime overhead and quick compilation startup). Share your experience using it!

Answer №2

This code snippet monitors changes in typescript test files and executes them using ts-node (ensure ts-node is installed):

"scripts": {
"watch": "mocha -r ts-node/register test/*Test.ts --watch --watch-extensions ts"
}

Answer №3

Personally, I found that including a prefix such as **/

mocha -r ts-node/register "test/**/*.ts" --watch --watch-files **/*

Additionally, if you need to include multiple specific folders or files:

mocha -r ts-node/register "test/**/*.ts" --watch --watch-files src/**/*,test/**/*

Answer №4

--extensions option has been deprecated in the latest version of Mocha 8.

Instead, you should use the --watch-files flag.

"scripts": {
    "watch": "mocha -r ts-node/register test/*Test.ts --watch --watch-files *.ts"
}

Answer №5

In Mocha 7, if you want to use the --watch flag, you need to define either --watch-files or --extension. You can choose one of the following configurations:

"scripts": {
    "watch": "mocha -r ts-node/register test/*Test.ts  --watch --extensions ts"
}

or

"scripts": {
    "watch": "mocha -r ts-node/register test/*Test.ts  --watch --watch-files test"
}

According to the Mocha official documentation :

--watch, -w Rerun tests on file changes.

The --watch-files and --watch-ignore options can be used to control which files are watched for changes.

Tests may be rerun manually by typing ⓡ ⓢ ⏎ (same shortcut as nodemon).

--watch-files New in v7.0.0

List of paths or globs to watch when --watch is set. If a file matching the given glob changes or is added or removed mocha will rerun all tests.

If the path is a directory all files and subdirectories will be watched.

By default all files in the current directory having one of the extensions provided by --extension and not contained in the node_modules or .git folders are watched.

The option can be given multiple times. The option accepts a comma-delimited list: --watch-files a,b is equivalent to --watch-files a --watch-files b

Answer №6

I have recently created a .mocharc.json file with the following contents:

{
  "extension": ["ts"],
  "spec": "test/**/*.ts",
  "require": "ts-node/register"
}

With this setup, I am now able to execute Mocha either for a single run or in watch mode:

$ npx mocha
or
$ npx mocha --watch

Of course, I can also include this configuration in my package.json file as a script.

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

Having trouble retrieving documents from a nested collection in Firebase

I am attempting to retrieve all documents from Firebase that are based on a query. Here is my current firebase structure: https://i.stack.imgur.com/tXrX8.png Even though I have two documents inside the "ListaFavorite" collection, when I check using empty ...

The React Functional Component undergoes exponential re-renders when there is a change in the array

I'm encountering a problem with one of my functional components. Essentially, it maintains an array of messages in the state; when a new message is received from the server, the state should update by adding that new message to the array. The issue ar ...

If the numeral variable is used within an HTML function, a 'numeral is not defined' error may occur

Numeral.js is a key tool for me, utilized in both the viewmodels and occasionally in the HTML of my knockout components. <div data-bind="text: numeral(totalCurrent()).format('$0,0.00')"></div> While using webpack to bundle my HTML a ...

When multiple input fields with an iterative design are using the same onChange() function, the specific event.target.values for each input

I'm in the process of developing a dynamic select button that adjusts based on the information entered into the iterative input fields I've set up. These input fields all utilize the same onChange() function. for (let i = 0; i < selectCount; i ...

Challenges with React Event Listener Types

https://i.sstatic.net/cVlpr.png useEffect(() => { const handleEscClose = (e: KeyboardEvent) => { if (e.key === 'Escape') changeVisibility(); }; if (isVisible) document.addEventListener('keydown', handleEscClos ...

The header remains unchanged even after verifying the user's login status

Currently, I am using Angular 11 for the front-end and Express for the back-end. I am facing an issue with determining if a user is logged in so that I can display the correct header. Even after logging in and setting a cookie in the browser upon redirecti ...

Having trouble iterating over fields of an interface in TypeScript?

I am currently facing an issue while trying to loop through the keys of an object that contains an interface. TypeScript seems to be unable to recognize the type of the key. interface Resources { food?: number water?: number wood?: number coal?: n ...

Tips for sending a function as a value within React Context while employing Typescript

I've been working on incorporating createContext into my TypeScript application, but I'm having trouble setting up all the values I want to pass to my provider: My goal is to pass a set of values through my context: Initially, I've defined ...

Enhancing JSON Formatting with Angular 4 and Typescript

In the process of developing my Angular 4 application, I am interfacing with a REST API through JSON requests. As I work on creating JSON objects to send via POST requests, I find myself putting in quite a bit of manual effort to construct them... I KNOW ...

Is there a more effective alternative to using the ternary condition operator for extended periods of time?

Do you know of a more efficient solution to handle a situation like this? <tr [style.background]="level == 'ALARM' ? 'violet' : level == 'ERROR' ? 'orange' : level == 'WARNING' ? 'yellow' ...

Encountering an issue with Next.js, Typescript, and mongoose when attempting to use `let cached = global.mongoose

I attempted to create a cached mongoose connection for my Next.js + Typescript application, but the code I used was: let cached = global.mongoose; if (!cached) { cached = global.mongoose = { conn: null, promise: null }; } The use of global.mongoose res ...

"Encountering connectivity issues between NestJs and TypeORM when trying to establish a

My current challenge involves connecting to MySQL. I have set the database connection variables in a .env file located in the root directory, and I am initializing the connection in the app.module.ts file. The problem arises when I attempt to create or run ...

What is the best way to implement typing in getServerSideProps using Next.js with TypeScript?

I'm currently working on a project using NextJs and TypeScript, but I've encountered an issue with types in the getServerSideProps function. In my code snippet for getServerSideProps, I am retrieving data using context.query. However, despite my ...

Is it possible to include the term 'public' exclusively within a .ts file in a TypeScript TSLint React environment?

I'm struggling to understand why I am encountering an error in VSCode while working on a react typescript project with tslint setup. The error message states: 'public' can only be used in a .ts file. [Also, I'm wondering why I' ...

Setting button height dynamically in React Native

I've implemented a button using React Native Elements in my layout. Here's the code snippet: <Button title="Login" buttonStyle={{ backgroundColor: Colour.green }} containerStyle={{ ...

The TypeScript error code TS2345 indicates that the argument type 'JQueryXHR' cannot be assigned to the parameter type 'Promise<any>'

In a coding tutorial, an example code snippet demonstrates how to execute a JQuery getJSON() call and then transform the result into a Promise, which is later converted into an Observable. /// <reference path="../typings/tsd.d.ts" /> import { Compo ...

difficulties arise when trying to use ngOnChanges to update an array

My code includes an array that is being updated from another component, with new Strings being added to it using the array.push() method. I have verified this update by testing it with a button, however, ngOnChanges does not seem to detect any change in ...

problem encountered when running "ionic cordova build android --prod --release"

A chat application has been developed using Ionic2. Upon attempting to generate a production build with ionic cordova build android --prod --release, the following error is encountered. Error: ./node_modules/rxjs/observable/BoundCallbackObservable.js ...

What is the best way to retrieve property names that are not nullable from a type?

I am seeking to create a custom mapped conditional type in TypeScript that will allow me to extract property names from a type, while accounting for properties that can potentially have a value of null. For example: interface Person { name: string a ...

Do we really need TypeScript project references when transpiling with Babel in an Electron project using Webpack?

Currently, I am in the process of setting up my project configuration and have not encountered any errors so far. However, based on my understanding of the Typescript documentation... It appears that Project references are not essential when using babel-l ...