我正在尝试使用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();
});
但是它没有完成这项工作。任何想法如何做到这一点? 预先感谢。
答案 0 :(得分:1)
您的用于设置userName和password的中间件函数是在路由处理程序之后声明的,所以我猜测它没有被调用。在声明路线之前将其移动,例如
app.use(function(req, res, next) {
req.user = {
'userName': 'xxxx',
'password': 'xxxx'
};
next();
});
app.use('/v2/config/aw/', ClusterNode);
答案 1 :(得分: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);