超级测试中未定义的请求正文

Request body undefined in supertest

我正在用 supertest 测试一个 express API。我正在尝试将 body 参数传递到测试中,如下面的代码片段所示,但似乎 body 参数没有正确传递,因为我收到一条错误消息,指出 body 参数未定义。

运行用命令mocha --recursive测试returns出现如下错误:

Cannot read property 'email' of undefined


下面是来自文件 email-suite.js 的代码引用 supertest

'use strict';
var express = require("express");
var bodyParser = require('body-parser');
var mongoose = require("mongoose");

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var supertest = require("supertest");
var chai = require("chai");
var should = chai.should();

var api = require("../server.js");

describe("Email Module", function() {
    this.timeout(25000);

    before(function(done){
        mongoose.createConnection(/* connectionstring */);

        mongoose.connection.on('open', function(err) {
            if(err) console.log(err);
            console.log('connected to server');
        });

        done();
    });

    it("Check Email Count", function(done) {
        var body = { email: "email@email.com" };

        supertest(api)
            .post("/emailCount")
            .set('Accept', 'application/json')
            .send(body)  // body is undefined
            .expect(200)
            .expect('Content-Type', /json/)
            .end(function(err, res) {
                if(err) return done(err);
                res.body.count.should.equal(2);
                done();
            });
    });
});

下面是来自文件 email-api.js

的代码
'use strict';
var express = require("express");
var bodyParser = require('body-parser');
var router = express.Router();
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

router.post('/emailCount', function(req, res) {
    var email = req.body.email; // req.body is undefined
}

module.exports = router;

下面是文件 server.js

中的代码
var express = require("express");
var app = express();

app.set("port", process.env.PORT || 3000);

var router = require("./user/email-api");

app.use('/', router);

app.listen(app.get("port"), function() {
    console.log("App started on port " + app.get("port"));
});

module.exports = app;

body-parser 始终放在 express object 之后和主服务器文件中的每个路由之前

 var app = express();
 app.use(bodyParser.json());
 app.use(bodyParser.urlencoded({extended: true}));

//路由器任务从这里开始

否则总是会得到 undefined,因为首先调用路由器,然后解析正文。