Troubleshooting SuperTest Errors: A Quick Guide
Are you tired of searching how to solve error such as
TypeError: server.close / app.close() is not a function
TypeError: Cannot read properties of undefined (reading 'address')
TypeError: app.address / server is not a function
Attempted to log "Server is running on port 3000".
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
Subscribe to my newsletter
Read articles from Mathanraj T directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Mathanraj T
Mathanraj T
I am a student who is keen on learning and exploring new things and excited about entering the world of developers where I can find the best way to learn new technology, tools and keep updated. Excited to learn by doing. Always open to learning and feedback.