Encountering an error in testing with Typescript, Express, Mocha, and Chai

After successfully creating my first server using Express in TypeScript, I decided to test the routes in the app.

import app from './Server'

const server = app.listen(8080, '0.0.0.0', () => {
    console.log("Server is listening on standard port 80...");
});

export default server;

Now, let's test the routes:

import express from 'express';
import * as bodyParser from "body-parser";

const app = express();

app.use(bodyParser.json());

app.get("/", (req: express.Request, res: express.Response) => {
    res.status(200).send("SUCCESS");
});

export default app;

I wrote a test script for this:

import * as chai from 'chai';
import chaiHttp = require('chai-http');

chai.use(chaiHttp);

import server from '../src';

describe("LogAPI", () => {

    describe('Base express tests', () => {
        it("Should return 'SUCCESS' if GET /", async () => {
            return chai.request(server).get("/").then(res => {
                chai.expect(res.body).to.equal("SUCCESS");
            })
        });

        it("Should return status-code 200 by calling GET /", async () => {
            return chai.request(server).get("/").then(res => {
                chai.expect(res.status).to.equal(200);
            })
        });

    });
});

However, when trying to run the test with the command:

mocha --require ts-node/register ./../test/**/*.ts

I encountered an error message that says:

/Users/.../NotificationService/src/Server/index.js:5 var app = express_1.default(); ^ TypeError: express_1.default is not a function at Object. (/Users/.../NotificationService/src/Server/inde> x.js:5:28)

Despite the successful functioning of the server, how can I fix this testing issue?

Update 1: By removing the default() method from the compiled code, I was able to resolve some issues.

Subsequently, I encountered another error:

/Users/.../NotificationService/test/node_modules/@types/chai-http/index.d.ts:13 import * as request from 'superagent'; SyntaxError: Unexpected token import

Update 2: Here is my ts-config.json file:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs", 
    "outDir": "./../out“,
    "strict": true,
    "esModuleInterop": true   
  }
}

Answer №1

The issue concerning express stems from the fact that express does not utilize default exports, so the proper way to import it is as follows:

// app.js
import * as express from 'express'

Make sure to also add type definitions for a smooth compilation in Typescript by running:

npm install @types/express --save-dev
npm install @types/body-parser --save-dev
npm install @types/chai-http --save-dev

Update: I tested this locally with my tsconfig.json

// tsconfig.json
{
  "compilerOptions": {
      "module": "commonjs",
      "types": [
        "node",
        "mocha",
        "express"
      ],
      "target": "es5",
      "lib": [
        "es2015"       
      ],
      ...
  },
}

Using default export has its drawbacks explained in https://example.com/default-export-explanation

I hope this information proves helpful.

Answer №2

Trying to do a default import from express, but the module actually uses an export assignment. You can either swap import express from 'express'; with

import express = require('express');
or enable the esModuleInterop compiler option in your tsconfig.json.

Answer №3

Thanks to the advice from deerawan, I have made changes in my project structure by combining tsconfig.json and package.json into one file. This simple adjustment has successfully resolved the issue.

- tsconfig.json
- package.json
- src/
    - index.ts
- test/
    - test.ts

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

The database did not respond, causing the API to resolve without sending a response for the specified endpoint (/api/dates). This could potentially lead to requests becoming stalled in Next

I have been attempting to retrieve a list of dates from my database in a straightforward manner, but unfortunately, I am not receiving any response (even after trying to log the response data to the console). The only feedback I seem to be getting when sel ...

Unlock the Power of Angular with Custom Decorators: Accessing ElementRef Made Easy

I am currently working on implementing a decorator for Host CSS Variable Binding in Angular5. However, I am facing difficulties in properly implementing it with the given code. Is there a way to define ElementRef from within the decorator itself? export f ...

Having trouble sending a POST request with body parameters in Node.js? The error "undefined req.body.param" might be popping up when you're

I've encountered an issue with my server.js code: const bodyParser = require('body-parser'); const cors = require('cors'); const morgan = require('morgan'); var express = require('express') , http = requir ...

Context for Apollo server has not been defined

Following the upgrade to Apollo v4 and migration guide, my project was functioning properly. However, the context is now undefined. const { url } = await startStandaloneServer(server, { listen: { port: 3000 }, context: async ({ req }) => { try ...

Is it beneficial to use virtuals for relationships in Mongoose?

When working with the mongodb(mongoose) & NodeJS(express) stack, I have noticed that one to many relationships are often implemented in a certain way, as shown in this simplified example: const { Schema } = require("mongoose"); const DB = re ...

Preventing inline style/script from being applied in CSP with nonce in a node.js application

My goal is to enhance the security of my website, which I have built using node.js/express/npm, by implementing a proper CSP. I am utilizing the npm helmet package and attempting to set up the CSP using nonce. Despite my efforts to include the nonce in var ...

Preventing text from wrapping in a TypeScript-generated form: Tips and tricks

I’m currently working on a ReactJS project and my objective is simple: I want all three <FormItem> components to be displayed in a single line without wrapping. However, I am facing the following output: https://i.stack.imgur.com/mxiIE.png Within ...

The debate between using backticks and colons in TypeORM queries

Lately, I've been crafting queries utilizing backticks const firstUser = await connection .getRepository(User) .createQueryBuilder("user") .where(`user.id = '${id}'`) .getOne(); However, in the typeorm documentatio ...

What is the best way to compare an array with comma-separated values in JavaScript?

I have a scenario where I have two arrays, one for categories and the other for products. Each product contains multiple categories as a comma-separated string. My goal is to match a specific category with each product's product_category value and the ...

Issues encountered while establishing a connection to an API in React Native

When attempting to log in a user by connecting to my API, I encountered some issues. It seems that every time my laptop has a different IP address, I need to make changes in the file where the fetch or XMLHttpRequest is located in order for the login proce ...

Encountered an error when incorporating nguniversal/express-engine into an Angular project: "Unable to locate the BrowserModule import in /src/app/app.module.ts"

One of the initial questions Purpose The main aim is to integrate SSR into my Angular project using ng add @nguniversal/express-engine --clientProject [name] (to enable dynamic prerendering of meta tags). Expected Outcome I anticipated the command to run ...

How to extract the chosen option from a bound list within an Angular application

Our goal is to avoid using 2-way binding in our component setup: <select type="text" formControlName="region" (change)="regionChanged($event)"> <option *ngFor="let region of regionsDDL" [ngValue]="region">{{region.name}}</option> ...

What is a suitable alternative to forkJoin for executing parallel requests that can still complete even if one of them fails?

Is there a more robust method than forkJoin to run multiple requests in parallel and handle failed subscriptions without cancelling the rest? I need a solution that allows all requests to complete even if one fails. Here's a scenario: const posts = th ...

Trouble with loading images on hbs/nodejs

I'm currently working on a web application using NodeJs and express-handlebars. However, I am facing an issue with images not displaying correctly on the HTML page that is being rendered using handlebars. Here is the structure of my app: The root fo ...

What steps should I follow to integrate Semantic UI into a project using React and Express?

As a newcomer to Semantic/React/Express, I am wondering how to incorporate the stylesheet for Semantic in React. Do I need an html file that directly references the Semantic css and JavaScript files? Currently, I am not utilizing any html files. In my mai ...

Is there a way to fix the error "The requested resource does not have the 'Access-Control-Allow-Origin' header" within Express using Firebase functions?

Trying to send an email through nodemailer using Firebase functions, but encountering errors. The data for the email will come from a form. Error message: Access to XMLHttpRequest at 'my-firebase-functions' from origin 'my-angular-web-app&a ...

What is the best approach for adding variable rows to a Postgres junction table: should you concatenate a query string, utilize multiple queries, or explore alternative methods

Below is the code snippet for handling a variable-length list of tags and inserting data into the database: // JSON object from req.body { "title": "title", "reference": "1213", "noteType": &q ...

Express API is mistakenly including a "data" section in the response of all GET requests, something that was not intended

I'm currently developing a REST API and encountering an unexpected result when I send a /GET request. Upon making a GET request to the API, it is returning { data: { [{myExpectedObjects},{myExpectedObjects}] } } However, I am anticipating ...

New data field is created with AngularFire2 update instead of updating existing field

I am facing an issue with updating a Firestore model in Angular 6. The model consists of a profile name and a list of hashtags. The "name" is stored as the value of a document field, while the "hashtags" are stored as keys in an object. However, every time ...

The NodeJs and Express API, integrated with Ejs files, encounters a crash when attempting to retrieve data from the database on the second attempt

I've been assigned the task of developing an API that retrieves data from a database and presents it on the frontend. This is my first time working with APIs, and I've encountered some challenges along the way. The database I'm using is call ...