0

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

4

1 回答 1

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

于 2019-12-20T10:19:01.123 回答