【问题标题】:Modifying The request object sent by express when testing API request-response修改测试API request-response时express发送的请求对象
【发布时间】:2018-09-20 07:23:13
【问题描述】:

我正在尝试使用 express 测试一个简单的 API 请求响应。 但是,请求必须在请求对象中有以下字段: user.userName 和 user.password, 这是我到目前为止的代码:

const express = require('express');
const log = require('../../../../logger');
const app = express();
const ClusterNode = require('../cluster-node');

// TODO: don't like these here. Needed to post. Put into global test startup if possible.
// TODO - OMRI: Reaplce this with the global test startup, when created.
const socketio = require('socket.io');
app.io = socketio.listen();
const bodyParser = require('body-parser');
app.use(bodyParser.json());


app.use('/v2/config/aw/', ClusterNode);
app.use(function(req, res, next) {
  req.user.userName = 'xxxx';
  req.user.password = 'xxxx';
  next();
});

describe('API - ClusterNode', () => {
  test('API - Get Cluster Nodes #1', () => {
    return request(app).get('/v2/config/aw/ClusterNode').then((response) => {
      expect(response.statusCode).toBe(200);
      expect(response.body.Node.length.toString()).toBe('0');
      expect(response.headers['content-type']).toMatch(/^application\/json/);
    });
  });
});

我已尝试添加此代码块:

app.use(function(req, res, next) {
  req.user.userName = 'xxxx';
  req.user.password = 'xxxx';
  next();
});

但是它没有完成这项工作。知道这是怎么做的吗? 提前致谢。

【问题讨论】:

    标签: node.js rest express


    【解决方案1】:

    如果您想在req.user 中使用用户对象:

    app.use(function(req, res, next) {
     req.user = {
       'userName': 'xxxx',
       'password': 'xxxx'
     };
    next();
    });
    app.use('/v2/config/aw/', ClusterNode);
    

    如果您希望它出现在您的 req.body 中,请使用:

    app.use(function(req, res, next) {
     req.body.user = {
       'userName': 'xxxx',
       'password': 'xxxx'
     };
    next();
    });
    app.use('/v2/config/aw/', ClusterNode);
    

    【讨论】:

      【解决方案2】:

      设置用户名和密码的中间件函数是在路由处理程序之后声明的,所以我猜它没有被调用。在声明路线之前移动它,例如

      app.use(function(req, res, next) {
        req.user = {
          'userName': 'xxxx',
          'password': 'xxxx'
        };
        next();
      });
      app.use('/v2/config/aw/', ClusterNode);
      

      【讨论】:

      • 按照您发布的代码后,我得到了 response.code(500),当我调试调用时,我没有路由到处理该请求的方法。
      • 我没有从你在请求中传递用户对象的地方得到。如果您使用的是正文解析器,这意味着您应该在 req.body 中传递它。 @OmriShneor
      • 正如 Dhaval 指出的那样,我看不到您实际创建 req.user 的位置,因此我更改了代码来创建它
      猜你喜欢
      • 2019-12-13
      • 2019-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-29
      • 2018-11-13
      • 2019-06-16
      • 1970-01-01
      相关资源
      最近更新 更多