supertest not found error testing express endpoint - javascript

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

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("/")
...

Related

sendFile function in express js is not working

When i try t run this code, i don't get any error but i get a blank screen when i open loclhost.
const path = require("path")
const express = require("express")
app = express()
app.get("/", (req, res) => {
let fullpath = path.join(__dirname, './index.html')
console.log(fullpath)
res.sendFile(fullpath)
console.log("File sent")
res.end()
})
app.listen(5500, () => {
console.log("Server started")
})
Im using linux, express version is 4.18.2, node version is 18.1.0
I executed the same code in a windows machine with same express version and it worked without any error. Maybe its something to do with linux compatibility or maybe how paths are different in windows and linux.
Things i have tried so far:
const path = require("path")
const express = require("express")
app = express()
app.get("/", (req, res) => {
let fullpath = path.join(__dirname, './index.html')
res.sendFile(fullpath, { root: '/' })
console.log("File sent")
res.end()
})
app.listen(5500, () => {
console.log("Server started")
})
const path = require("path")
const express = require("express")
app = express()
app.get("/", (req, res) => {
var options = {
root: path.join(__dirname)
}
let fileName = 'index.html'
res.sendFile(fileName, options)
console.log("File sent")
res.end()
})
app.listen(5500, () => {
console.log("Server started")
})
Simple Answer:
Remove res.end();
Try this code
const express = require("express")
app = express()
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html")
console.log("File sent")
})
app.listen(5500, () => {
console.log("Server started")
})

How can I securely start a Node Express server before running my Jest tests?

I have two files:
Simple Express app: app.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 an app.test.js
import axios from 'axios';
beforeAll( () => {
// Probably here I should start the server, but how?
});
test("test-my-api", async () => {
const response = await axios.get("http://localhost:3000")
expect(response.data).toBe("Hello World!")
}")
How can I run the app before testing the requests to the app in a secure manner? How is it done professionally?

Express importing app from server.js is giving me an error

I have created an express server in my server.js file, and I export app from it.
//server.js
require("dotenv").config();
const express = require("express");
const app = express();
const connectToDb = require("./connectToDb")
connectToDb().catch(console.dir)
app.use((req, res) => {
res.status(404).send("unable to find");
});
module.exports = app
I import app from server.js in the connectToDb.js file
//connectToDb.js
const app = require("./server")
const MongoClient = require("mongodb").MongoClient;
const client = new MongoClient(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
});
const port = process.env.PORT || 3000;
const connectToDb = async () =>{
try {
await client.connect();
console.log("Connected correctly to server");
app.listen(port, () => {
console.log(`Listening on port ${port}`);
})
} catch (err) {
console.log(err.stack);
} finally {
await client.close();
console.log("hello")
}
}
module.exports = connectToDb
It connects succesfully to the database, but when it reaches app.listen it gives me this error: TypeError: app.listen is not a function. I don't know why it gives me an error because I have exported app. What am I doing wrong?
That's because you have a cyclic dependency. The two files import each other, and inside server.js you make a call immediately on load. In the moment you call connectToDb inside of server.js, the server.js file has not fully executed yet and hence the module export has not yet happened. Either way it's something you should try to avoid (cyclic dependencies).
Just resolve the cycle by passing the app to the connectToDb function as a parameter instead of importing it:
//server.js
require("dotenv").config();
const express = require("express");
const app = express();
const connectToDb = require("./connectToDb")
connectToDb(app).catch(console.dir)
app.use((req, res) => {
res.status(404).send("unable to find");
});
module.exports = app
// connectToDb.js
const MongoClient = require("mongodb").MongoClient;
const client = new MongoClient(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
});
const port = process.env.PORT || 3000;
const connectToDb = async (app) =>{
try {
await client.connect();
console.log("Connected correctly to server");
app.listen(port, () => {
console.log(`Listening on port ${port}`);
})
} catch (err) {
console.log(err.stack);
} finally {
await client.close();
console.log("hello")
}
}
module.exports = connectToDb

Lost HTTP request body

I am using Groovy script to perform HTTP POST request with some data:
import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.ContentType.*
import groovyx.net.http.ContentType
import static groovyx.net.http.Method.*
def http = new HTTPBuilder('myhost.com')
http.request( POST ) {
uri.path = '/'
requestContentType = ContentType.JSON
body = [title: 'some data', desc: 'some more data']
log.info(body.title)
response.success = { resp,reader ->
log.info( "POST response status: "+resp.statusLine+"}")
}
}
This works just fine, Groovy results are below:
Logs:
INFO : some data
INFO : POST response status: HTTP/1.1 200 OK}
But when I see my web service logs the request body is undefined:
Here's the code:
const express = require('express');
const app = express();
var test = {0:'post'};
app.get('/', (req, res) => {
res.send('a');
console.log('request inbound');
});
app.post('/',(req,res) => {
res.send('test');
console.log('post in');
console.log(req.body);
});
// Listen to the App Engine-specified port, or 8080 otherwise
const PORT = process.env.PORT || 30000;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}...`);
});
I'm using Node.js v12.13 | npm v6.12 | express.js 4.17.1
I'm afraid you've omitted app.use(express.json()).
const express = require('express');
const app = express();
app.use(express.json())
var test = {0:'post'};
app.get('/', (req, res) => {
res.send('a');
console.log('request inbound');
});
...

REST api/postman - Cannot GET /the route Error

I am building a (RESTful) Node.js API, using this tutorial.
I have nade a server.js
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
const port = 8080;
app.listen(port, () => {
console.log('We are live on ' + port);
});
I can run my server and see the message :
We are live on 8080
my index.js
const noteRoutes = require('./note_routes');
module.exports = function(app, db) {
noteRoutes(app, db);
// Other route groups could go here, in the future
};
and my node_routes.js
//create a node
module.exports = function(app, db) {
app.post('/notes', (req, res) => {
// You'll create your note here.
res.send('Hello')
});
};
index.js and node_routes.js are both inside app\routes\
I have also downloaded the post man app, to make simple requests
and I get the error
Cannot POST /notes
what am I doing wrong??
I can not figure it out!
There is an error in your server.js
You are missing require('./app/routes')(app, {});
Should be:
require('./app/routes')(app, {});
app.listen(port, () => {
console.log('We are live on ' + port);
});

Categories

Resources