在节点js中使用假会话测试路由

时间:2014-01-10 09:42:51

标签: node.js testing express nodeunit superagent

我正在为我的服务器使用node js + express。我正在用superagent + node unit编写测试,我的路由需要会话来访问它,我可以伪造这个会话来测试我的路由/控制器吗? (可能是superagent没有这个功能,所以建议请另外一个工具)

1 个答案:

答案 0 :(得分:0)

这是使用express-session的最小工作示例:

app.js

const express = require("express");
const session = require("express-session");

const app = express();
app.use(
  session({
    secret: "keyboard cat",
    resave: false,
    saveUninitialized: true,
  }),
);

app.post("/signin", (req, res) => {
  req.session.auth = "123";
  console.info("sign in success");
  res.status(200).end();
});

app.get("/protected", (req, res) => {
  console.log("req.session.auth: ", req.session.auth);
  if (!req.session.auth) {
    return res.sendStatus(401);
  }
  res.json({ data: "protected data" });
});

module.exports = app;

app.test.js

const app = require("./app");
const superagent = require("superagent");
const { expect } = require("chai");

describe("21040811", () => {
  let server;
  const port = 4001;
  const agent = superagent.agent();
  before((done) => {
    server = app.listen(port, () => {
      console.info(`HTTP server is listening on http://localhost:${port}`);
      done();
    });
  });
  after((done) => {
    server.close(done);
  });
  it("should return 401 status code", () => {
    return agent.get(`http://localhost:${port}/protected`).catch((err) => {
      expect(err.response.status).to.be.equal(401);
    });
  });

  it("should sign in success and access /protected API correctly", () => {
    return agent
      .post(`http://localhost:${port}/signin`)
      .then((res) => {
        expect(res.status).to.be.equal(200);
      })
      .then(() => agent.get(`http://localhost:${port}/protected`))
      .then((res) => {
        expect(res.status).to.be.equal(200);
        expect(res.body).to.be.eql({ data: "protected data" });
      });
  });
});

覆盖率100%的集成测试结果:

 21040811
HTTP server is listening on http://localhost:4001
req.session.auth:  undefined
    ✓ should return 401 status code
sign in success
req.session.auth:  123
    ✓ should sign in success and access /protected API correctly


  2 passing (61ms)

-------------|----------|----------|----------|----------|-------------------|
File         |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-------------|----------|----------|----------|----------|-------------------|
All files    |      100 |      100 |      100 |      100 |                   |
 app.js      |      100 |      100 |      100 |      100 |                   |
 app.test.js |      100 |      100 |      100 |      100 |                   |
-------------|----------|----------|----------|----------|-------------------|

源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/21040811