Troubleshooting SuperTest Errors: A Quick Guide

The blog will give a solution to solve below mentioned error when you work with Super test

Are you tired of searching how to solve error such as

  1. TypeError: server.close / app.close() is not a function

  2. TypeError: Cannot read properties of undefined (reading 'address')

  3. TypeError: app.address / server is not a function

  4. Attempted to log "Server is running on port 3000".

  5. Error: listen EADDRINUSE: address already in use :::3000

And similar error this blog may help you to solve the problem

Step 1 : add a .env variable to differentiate whether the running environment is "test" or "development"

// app.js or index.js

//app here is express
const environment = process.env.ENVIRONMENT || "development"
    if(environment!== "test"){
        app.listen(port,()=>{ 
            ///...    
        } 
    )
}
export app;

Step 2 : No need to put beforeEach and afterEach to get server and close respectively in supertest test file

Step 3: Just import the app in supertest and use it inside the request method and supertest will internally create and close the server on each call

const request = require("supertest");
const app = require("../../app"); // Adjust the path accordingly

describe("Sample Test", () => {
  it("should return a status code of 200", async () => {
    const result = await request(app).get("/"); // Assuming '/' is a valid route in your app
    expect(result.statusCode).toBe(200);
  });
  // Add more test cases as needed
});

I am using version >= 6.0.0 of supertest while writing the blog

Hope this help to solve your issue in working with supertest : ). If yes then give it a like and i will meet you with a new blog