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



我正在使用节点js + express作为我的服务器。我正在使用超级代理+节点单元编写测试,我的路由需要会话才能访问它,我可以伪造此会话来测试我的路由/控制器吗?(可能是超级代理没有这个功能,所以建议请其他工具)

这是一个使用 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

最新更新