[SOLVED] Testing Express, MongoDB & TypeScript with supertest and Jest fails when I use app


I want to test my Express, MongoDB, TypeScript REST-Api, but I am having difficulty with a line of code where supertest takes app as parameter. The test fails and I get the 404 status code instead of 200.

const resVar = await supertest(app).get(`/`);

However when I replace the parameter app with http://localhost:${EXPRESS_APP_PORT}/api/v1/users the test passes and I get a 200 status code.
This is a small project and you can get & clone all the code on this Github repository.
Looking forward to your help.

server.ts (server initialization location/file) ⬇

import express, {Application} from 'express';
import cors from 'cors';
import {deserializeUserFunc} from './middleware/deserializeUser';
import {routes} from './routes/index';

const initServer = () => {
  const app: Application = express();
  app.use('/api/v1/users', routes);
  return app;

export {initServer}

index.ts (connection to MonGODB & listening to port occurs here, but not for testing environment.) ⬇

import {initServer} from './server';
import mongoose from 'mongoose';
import dotenv from 'dotenv';
const mongoDbPassword = process.env.MONGODB_PASSWORD;
import pinoLogger from './logger';

// connect to online mongoDB
mongoose.connect(`mongodb+srv://${MONGO_DB_USERNAME}:${mongoDbPassword}@emmethubclusterone.disfr.mongodb.net/${MONGO_DB_DATABASE}?retryWrites=true&w=majority` )
  .then(() => {
    pinoLogger.info(`Connected to ${MONGO_DB_DATABASE} database.`);
  .catch((err) => {
    pinoLogger.error(`${err} Error connecting to ${MONGO_DB_DATABASE} database!`);

const app = initServer();

app.listen(EXPRESS_APP_PORT, () => {
  pinoLogger.info(`App server is listening at http://localhost:${EXPRESS_APP_PORT}`);

product.test.ts (my file with the test that fails.) ⬇

import supertest from 'supertest';
import {initServer} from "../server" ;
import {MongoMemoryServer} from 'mongodb-memory-server';
import mongoose from 'mongoose';

const app = initServer();

describe('product', () => {

  beforeAll( async() => {
    const mongoServer = await MongoMemoryServer.create();
    await mongoose.connect(mongoServer.getUri())

  afterAll(async() => {
    await mongoose.disconnect();
    await mongoose.connection.close();

  describe('get product route', () => {
    describe('given the product exists', () => {
      it('should return a 200 and the product', async() => {
        const resVar = await supertest(app).get(`/`);



It might be because of the route you specified in product.test.ts. In index.ts you state app.use('/api/v1/users', routes); but in product.test.ts you target:

await supertest(app).get(`/`);

Try with

await supertest(app).get(`/api/v1/users`);

Answered By – perthos

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *