Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing HTTP requests in node.js with express

I have a simple authentication system I've made with a few post/get/dels on '/session' using express. I'd like to test this, but I can't seem to find a good easy way to simply test http.sendPut('/session', {data}) from the server. Does anyone have suggestions for a library to use?

I'm using Mocha/should for my tests, if that helps.

Here is my super simple auth-thingy that I want to test (it hooks into some other things):

//Login
app.post("/session", function(req, res) {
  if (req.body.username === "admin" && req.body.password === "admin") {
    req.session.user = "user";
    res.send("Successfully logged in!");
  } else {
    res.send(403, "Invalid username or password.");
  }
});
//Logout
app.del("/session", function(req, res) {
  req.session.user = null;
  res.send("Successfully logged out.");
});
//Am I logged in? Check for the client
app.get("/session", function(req, res) {
  if (req.session.user) {
    res.send(req.session.user);
  } else {
    res.send(403, "You are not logged in.");
  }
});

Thanks.

like image 872
Andrew Joslin Avatar asked Jul 10 '12 23:07

Andrew Joslin


People also ask

What is difference between HTTP and Express in NodeJS?

Frameworks such as Express provide appropriate packages based on HTTP modules, which are suitable for developing small and medium-sized projects. Frameworks such as Next are based on Express, Koa, etc. to do secondary packaging, suitable for the development of more complex projects.


1 Answers

Express.js is tested with supertest and supertest is based on superagent.

If you need some examples you can find them in the Express.js test code.

All the tests that require request = require('./support/http'); are using supertest.

like image 90
Pickels Avatar answered Sep 19 '22 23:09

Pickels