简体   繁体   English

使用express在node.js中测试HTTP请求

[英]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. 我有一个简单的身份验证系统,我使用express在'/ session'上使用了一些post / get / dels。 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. 我想测试一下,但我似乎找不到一个简单的方法来简单地从服务器测试http.sendPut('/session', {data}) Does anyone have suggestions for a library to use? 有没有人建议使用图书馆?

I'm using Mocha/should for my tests, if that helps. 我正在使用Mocha / should进行测试,如果有帮助的话。

Here is my super simple auth-thingy that I want to test (it hooks into some other things): 这是我想要测试的超级简单的auth-thingy(它挂钩到其他一些东西):

//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. 谢谢。

Express.js is tested with supertest and supertest is based on superagent . Express.js使用supertest进行测试, supertest基于superagent

If you need some examples you can find them in the Express.js test code . 如果您需要一些示例,可以在Express.js 测试代码中找到它们。

All the tests that require request = require('./support/http'); 所有需要request = require('./support/http'); are using supertest. 正在使用超级。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM