I tried to set up 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 localhost:3000 in my browser I can see 'Hello World!'
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);
});
});
});