在超级

时间:2016-09-13 12:50:51

标签: node.js express chai supertest

使用命令mocha运行测试--recursive给出

  

无法读取未定义

的属性'email'

以下是引用supertest的文件email-suite.js中的代码

'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;

1 个答案:

答案 0 :(得分:4)

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

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

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

其他明智的做法总是得到undefined,因为路由器首先调用,然后解析主体。