如何在摩卡/柴 API 单元测试中模拟 req.session



使用 Mocha/Chai 进行 REST API 单元测试,我需要能够模拟req.session.someKey几个端点。我怎样才能嘲笑req.session

我正在为使用快速会话的 NodeJS Express 应用程序编写 REST API 单元测试。其中一些端点需要使用存储在req.session.someKey中的数据,如果req.session.someKey未定义,端点设置为返回 400,所以我需要能够模拟它才能成功完成测试。

示例代码:

router.get('/api/fileSystems', utilities.apiAuth, (req, res) => {
  let customer = req.session.customer;
  let route = (customer === 'NONE') ? undefined : customer;
  if(route == undefined){
    res.status(400).send('Can't have customer of undefined');
  } else {
    let requestOptions = setRequestOptions(route);
    queryFileSystemInfo(requestOptions, (info) => {
      res.status(200).send(info);
    });
  }
});

我尝试过:

describe('/GET /api/fileSystems', () => {
  it('It should return information about the filesystem for a customer'), (done) => {
    chai.request(server)
      .get('api/fileSystems')
      .set('customer', '146')
      .end((err, res) => {
        res.should.have.status(200);
        done();
      });
  });
});

我试图使用该.set()来设置 req.session,但我相信 .set 只是设置了标题,所以我不相信我可以这样更新它,除非我错过了什么。

在快速设置中,您通常像这样插入会话中间件

app.use(session(config))

相反,您可以将会话中间件放在方便的可访问位置,并为其制作包装器,如下所示:

app.set('sessionMiddleware') = session(config)
app.use((...args) => app.get('sessionMiddleware')(...args)

测试将需要访问快速实例,您可以通过重构/app.js导出函数来执行此操作。

function app () {
  const app = express()
  // ... set up express
  return app
}
// run app if module called from cli like `node app.js`
if (require.main === module) instance = app()
module.exports = app

然后在测试中,您可以覆盖 app.sessionMiddleware

describe('/GET /api/fileSystems', () => {
  it('It should return information about the filesystem for a customer'), (done) => {
    app.set('sessionMiddleware') = (req, res, next) => {
      req.session = mockSession // whatever you want here
      next()
    }
    chai.request(server)
      .get('api/fileSystems')
      .set('customer', '146')
      .end((err, res) => {
        res.should.have.status(200);
        done();
      });
    // then you can easily run assertions against your mock
    chai.assert.equal(mockSession.value, value)
  });
});

我在网上看到的其他选项涉及设置 cookie 以匹配存储在数据库中的会话,这种方法的问题在于,当数据库中的会话过期时,您最终会遇到问题,因此随着时间的流逝,测试会失败夹具变得陈旧。使用上述方法,您可以通过在测试中设置过期时间来解决此问题。

模拟会话非常使用完全来模拟会话对象

 let mockSession = require('mock-session');
 describe('/GET /api/fileSystems', () => {
  it('It should return information about the filesystem for a customer'), (done) => {
    let cookie = mockSession('my-session', 'my-secret', {"count":1});  // my-secret is you session secret key. 
    chai.request(server)
      .get('api/fileSystems')
      .set('cookie',[cookie])
      .end((err, res) => {
        res.should.have.status(200);
        done();
      });
  });
});

对于这个项目,我最终不得不在我们的服务器.js文件中设置req.session.customer,该文件具有使用中间件函数设置当前会话的app.use()调用。我实际上无法找到在测试时直接改变 req.session 对象的包。

最新更新