supertest not found error testing express endpoint supertest not found error testing express endpoint express express

supertest not found error testing express endpoint


you should refactor index.js and create app.js

app.js

const express = require("express");const app = express();app.get("/", (req, res) => res.send("Hello World!"));

index.js

const app = require('./app')const port = process.env.PORTapp.listen(port, () => { console.log(`listening on ${port}) . })

the reason why we restructure the code like this is we need to access to express app() but we do not want "listen" to be called.

in your test fileconst request = require("supertest");const app = require("../src/app");describe("/", () => {  test("it says hello world", done => {    request(app)      .get("/")      .expect(200)      .end(function(err, res) {        console.log("err", err);      });  });});


It's because app instance in your test is different from the one running in your index.js

Export app from your index.js:

const server = app.listen(port, () => console.log(`Example app listening on port ${port}!`));module.exports = server;

And import in your test:

const server = require('./index.js');// pass your server to test...request(server)  .get("/")...