Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

node.js - supertest not found error testing express endpoint

I tried to setup jest, supertest and express but failed. I have these 2 simple file

index.js

const express = require("express");
const app = express();
const port = 3000;

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

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

and index.test.js

const express = require("express");
const app = express();
const request = require("supertest");

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

when I run the test I'm getting this error. err Error: expected 200 "OK", got 404 "Not Found"

What's wrong?

I visit to localhost:3000 in my browser I can see 'Hello World!'

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.PORT
app.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 file

const 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);
      });
  });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...