TypeError: describe is not a function in the Mocha testing framework

Encountering an issue with mocha-typescript throwing an error indicating that describe is not defined.

    TypeError: mocha_typescript_1.describe is not a function
    at DatabaseTest.WrongPath (test/database_test.ts:21:9)
    at Context.<anonymous> (node_modules/mocha-typescript/index.ts:218:22)

Here's my tsconfig.json configuration:

    {
      "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "outDir": "dist",
        "sourceMap": true,
        "lib": ["es6"],
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "typeRoots": [
          "./node_modules/@types"
        ],
        "types": [
          "node", "mocha", "chai"
        ]
      },
      "include": [
        "src/**/*.ts",
        "test/**/*.ts"
      ],
      "exclude": [
        "node_modules"
      ]
    }

And here's my package.json setup:

    {
      //omitted
      "main": "App.js",
      "scripts": {
        "pretest": "tsc",
        "test": "nyc mocha --require ts-node/register test/**/*_test.ts ",
        "watch": "mocha-typescript-watch",
        "prepare": "tsc"
      },

      // ommitted

      "dependencies": {
        "@types/chai": "^4.0.6",
        "@types/jsesc": "^0.4.29",
        "@types/mocha": "^2.2.44",
        "@types/node": "^8.0.53",
        "@types/sqlite3": "^3.1.1",
        "chai": "^4.1.2",
        "express": "^4.16.2",
        "express-longpoll": "0.0.4",
        "jsesc": "^2.5.1",
        "mocha": "^4.0.1",
        "mocha-typescript": "^1.1.12",
        "nyc": "^11.3.0",
        "reflect-metadata": "^0.1.10",
        "sequelize": "^4.26.0",
        "sequelize-typescript": "^0.6.1",
        "source-map-support": "^0.5.0",
        "sqlite3": "^3.1.13",
        "ts-events": "^3.2.0",
        "ts-node": "^3.3.0",
        "typescript": "^2.6.2",
        "typings": "^2.1.1"
      }
    }

database_test.ts contents:

    //Unit testing script for Database.ts
    /// <reference path="../node_modules/mocha-typescript/globals.d.ts" />
    //// <reference path="../node_modules/@types/mocha/index.d.ts" />

    import { suite, test, describe, slow, timeout  } from "mocha-typescript"
    import { assert } from "chai";
    import 'mocha'

    @suite(slow(1000), timeout(3000))
    export class SampleTest {

        @test testFunc(){
            describe("Sample function", ()=>{
                it("Should succeed without any problems", (done) => {
                    assert.isTrue(true);
                    done();
                })
            });
        }
    }

Full log details:

    > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="58282a37323d3b2c186976687668">[email protected]</a> pretest /home/user/folder/project
    > tsc


    > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3343415c5956504773021d031d03">[email protected]</a> test /home/user/folder/project
    > nyc mocha --require ts-node/register test/**/*.ts



      SampleTest
       1) testFunc            

      0 passing (13ms)
      1 failing

      1) SampleTest
           testFunc:
         TypeError: mocha_typescript_1.describe is not a function
          at DatabaseTest.WrongPath (test/database_test.ts:21:9)
          at Context.<anonymous> (node_modules/mocha-typescript/index.ts:218:22)


    ----------|----------|----------|----------|----------|----------------|
    File      |  % Stmts | % Branch |  % Funcs |  % Lines |Uncovered Lines |
    ----------|----------|----------|----------|----------|----------------|
   All files |  Unknown |  Unknown |  Unknown |  Unknown |                |
    ----------|----------|----------|----------|----------|----------------|
    npm ERR! Test failed.  See above for more details.

Various attempts have been made to resolve the issue such as modifying typeRoots, types in tsconfig.json, adding import mocha, and trying different type definition files. However, none of them have succeeded, leading to confusion and complexities.

The struggle with getting typescript-mocha functioning seamlessly continues, with results being inconsistent. A comprehensive explanation is sought after to unravel the confusion around the configuration.

Answer №1

The issue was caused by a duplicate keyword declaration. It turns out that simply using import 'mocha' is sufficient to declare the describe keyword.

All I had to do was modify the import statement from

import { suite, test, describe, slow, timeout  } from "mocha-typescript"

to

import { suite, test, slow, timeout  } from "mocha-typescript"

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

developed a website utilizing ASP MVC in combination with Angular 2 framework

When it comes to developing the front end, I prefer using Angular 2. For the back end, I stick with Asp MVC (not ASP CORE)... In a typical Asp MVC application, these are the steps usually taken to publish the app: Begin by right-clicking on the project ...

Strategies for resolving type issues in NextJs with Typescript

In my project using Next.js with TypeScript, I encountered an issue while trying to utilize the skipLibCheck = false property for enhanced checking. This additional check caused the build process to break, resulting in the following error: Error info - U ...

Importing the isPropertyUpdated method in Angular 4

My challenge lies in utilizing the isPropertyUpdated function within Angular 4. However, I have encountered a roadblock as Angular 4 does not facilitate deep imports. An example of an import that fails to work on Angular 4 is: import {isPropertyUpdated} ...

Did the IBM MobileFirst client miss the call to handleFailure?

I am currently utilizing the IBM MFP Web SDK along with the provided code snippet to send challenges and manage responses from the IBM MobileFirst server. Everything functions properly when the server is up and running. However, I have encountered an iss ...

What is the best way to pass props to a styled component (e.g., Button) in Material-UI

One of my tasks involves creating a customized button by utilizing the Button component with styled components. export const CustomButton = styled(Button)({ borderRadius: "17px", fontWeight: 300, fontSize: ".8125rem", height: &q ...

Guidelines on declining a pledge in NativeScript with Angular 2

I have encountered an issue with my code in Angular 2. It works fine in that framework, but when I tried using it in a Nativescript project, it failed to work properly. The problem arises when I attempt to reject a promise like this: login(credentials:Cr ...

Angular production application is experiencing issues due to a missing NPM package import

Objective I am aiming to distribute a TypeScript module augmentation of RxJS as an npm package for usage in Angular projects. Challenge While the package functions correctly in local development mode within an Angular application, it fails to import pro ...

"When attempting to render a Node inside the render() method in React, the error message 'Objects are not valid as a React child' is

On my webpage, I have managed to display the following: export class OverworldComponent extends React.Component<OverworldComponentProps, {}> { render() { return <b>Hello, world!</b> } } However, instead of showing Hello, ...

Angular 5 error: The property you are trying to access is not defined in

I've been working on a simple class and I'm stuck trying to figure out why the "currentHost" variable is showing as non-existent. export class AppModule { public static currentHost: string = 'http://localhost:8080/'; constructor() ...

Overriding TypeScript types generated from the GraphQL schema

Currently, I am utilizing the graphql-code-generator to automatically generate TypeScript types from my GraphQL schema. Within GraphQL, it is possible to define custom scalar types that result in specific type mappings, as seen below in the following code ...

Using external URLs with added tracking parameters in Ionic 2

I am looking to create a unique http link to an external URL, extracted from my JSON data, within the detail pages of my app. Currently, I have the inappbrowser plugin installed that functions with a static URL directing to apple.com. However, I would lik ...

What is the best way to implement forwardRef in a distinct select component?

Currently, I am utilizing react, typescript, and styled-components to work on my project. Specifically, I am aiming to create a select component for use in React Hook Form. Initially, everything seemed to be in order, but I encountered an error from typesc ...

Specializing Generic Types in Typescript

I'm interested in exploring specialization within Typescript generics, allowing for implementations to vary based on specific type criteria. Here's a simple illustration: const someFunction = <A>() => { return 0; } // something simila ...

Retrieve a specific subset of a union based on the class in a generic function

This question shares similarities with another post I made, but this time focusing on using classes instead of plain objects. class Exception1 extends Error { constructor(message: string, public arg1: string) { super(message); } } class Ex ...

What is the reason behind the return type of 'MyType | undefined' for Array<MyType>.find(...) method?

Currently, I am in the process of developing an Angular application using TypeScript. As part of this project, I have defined several classes along with corresponding interfaces that align perfectly with their respective properties: Map: export class Map ...

tips for concealing a row in the mui data grid

I am working on a data grid using MUI and I have a specific requirement to hide certain rows based on a condition in one of the columns. The issue is that while there are props available for hiding columns, such as hide there doesn't seem to be an eq ...

The combination of arrays and array methods in intersection types may encounter difficulty in accessing all fields

I have two different types, both in the form of arrays of objects with specified fields, combined into an intersection type in Typescript. When I access an element from the array, I can retrieve the second field without any issues. However, when I try to ...

In Angular, when using multiple-selection mode in mat selection, the Error Value should always be in the form of

**Everything is working fine except for one error in the console. How can I remove this error? Can anyone please help me? Save, Edit, and searching are working perfectly fine. ** public campaignCategoryFormGroup$: FormGroup = this.fb.group({ // 'c ...

A more efficient method for querying documents based on ids that are not in a given list and then sorting them by a specific publish date

After implementing the code provided below, I noticed that the performance tests indicate each request takes a second or longer to complete. My goal is to enhance this speed by at least 10 times. The bottleneck seems to be caused by the NOT operator resu ...

Secure Your Passwords with Encryption in NestJS using @nestjs/mongoose before saving them

Seeking to encrypt passwords before saving using @nestjs/mongoose. Came across examples written in pseudocode like this: UsersSchema.pre('save', (next: any) => { if (!this.isModified('password')) return next(); this.password = en ...