在编写使用supertest的测试时访问req.session对象

时间:2016-08-24 08:32:11

标签: node.js express supertest

我刚开始使用supertestnock在我的快速应用程序中为中间件编写单元测试。

首先检查我的路由器设置处理的所有请求是否存在会话属性(我正在使用快速会话)。

app.use('/api', helpers.hasAccessToken, require('./routes.js'));

助手只是这样做:

module.exports.hasAccessToken = function(req, res, next) {
  if(req.session.accessToken){
    next();
  } else {
    res.status(401).send('LOGIN_SESSION_ENDED');
  }
};

在我的测试规范中,我有:

var app = require('./index.js'),
  request = require('supertest')(app),
  expect = require('chai').expect,
  nock = require('nock');


    describe('GET requests', function(){
      beforeEach(function(){
        nock('https://somedomain:port')
          .get('/someendpoint')
          .reply(200, {foo:'bar'});
      });
      it('should return a 200 HTTP status code', function(done){
        request
          .get('/api/someendpoint')
          .end(function(err, res){
            expect(res.status).to.equal(200);
            done();
          });
      });
    });

这个错误的状态为401,而我知道这个错误归结为在运行测试之前未设置的req.session.accessToken属性。

那么我怎样才能让req对象用会话对象做我喜欢的事情呢?

由于

1 个答案:

答案 0 :(得分:0)

工作流程为:用户登录=>在服务器端设置req.session.accessToken =>通过set-cookie响应标头(由express-session设置的cookie)响应客户端=>调用受/api/someendpoint Cookie保护的accessToken端点。 =>调用hasAccessToken中间件=>其余代码逻辑。

这是解决方案:

app.js

const express = require("express");
const session = require("express-session");
const helpers = require("./helpers");
const app = express();

app.set("trust proxy", 1);
app.use(
  session({
    secret: "keyboard cat",
    resave: false,
    saveUninitialized: true,
  }),
);

app.post("/signin", (req, res) => {
  req.session.accessToken = "123123";
  console.info("signin success");
  res.status(200).end();
});

app.use("/api", helpers.hasAccessToken, require("./routes"));

const server = app.listen(3000, () => {
  console.info(`HTTP server is listening on http://localhost:${server.address().port}`);
});

module.exports = server;

helpers.js

module.exports.hasAccessToken = function(req, res, next) {
  console.log("req.session.accessToken", req.session.accessToken);
  if (req.session.accessToken) {
    next();
  } else {
    res.status(401).send("LOGIN_SESSION_ENDED");
  }
};

routes.js

const { Router } = require("express");

const router = Router();

router.get("/someendpoint", (req, res) => {
  res.sendStatus(200);
});

module.exports = router;

app.test.js

const app = require("./app");
const request = require("supertest");
const expect = require("chai").expect;

describe("GET requests", function() {
  const agent = request(app);
  let cookies;

  before((done) => {
    agent.post("/signin").expect(200, (err, res) => {
      if (err) return done(err);
      expect(res.headers).to.have.property("set-cookie");
      cookies = res.headers["set-cookie"].pop().split(";")[0];
      done();
    });
  });
  after((done) => {
    app.close(done);
  });

  it("should return a 200 HTTP status code", function(done) {
    console.log(cookies);
    agent
      .get("/api/someendpoint")
      .set("Cookie", [cookies])
      .end(function(err, res) {
        if (err) return done(err);
        expect(res.status).to.equal(200);
        done();
      });
  });
});

具有覆盖率报告的集成测试结果:

HTTP server is listening on http://localhost:3000
  GET requests
signin success
connect.sid=s%3Ahw94RpxRocC4hMTkCmMx4Ot85aGYG6s5.eE91ELDNjuQ1fWqEsRZdwtwKokLXR6%2Bao9NGdvl%2Bflc
req.session.accessToken 123123
    ✓ should return a 200 HTTP status code


  1 passing (33ms)

-------------|----------|----------|----------|----------|-------------------|
File         |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-------------|----------|----------|----------|----------|-------------------|
All files    |    93.33 |       50 |      100 |    97.67 |                   |
 app.js      |      100 |      100 |      100 |      100 |                   |
 app.test.js |    90.48 |       50 |      100 |      100 |             11,27 |
 helpers.js  |       80 |       50 |      100 |       80 |                 6 |
 routes.js   |      100 |      100 |      100 |      100 |                   |
-------------|----------|----------|----------|----------|-------------------|

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