Request body undefined in supertest
<p>I am testing an express API with supertest. I am trying to pass in body parameters into the test, as can be seen in the code snippets below, but it appears that the body parameters don't get passed in correctly since I get an error message that the body parameters are undefined.</p>
<p>Running the test with command <code>mocha --recursive</code> returns the following error:</p>
<blockquote>
<p>Cannot read property 'email' of undefined</p>
</blockquote>
<hr />
<p><strong>Below is the code from file email-suite.js referencing supertest</strong></p>
<pre class="lang-js prettyprint-override"><code>'use strict';
var express = require(&quot;express&quot;);
var bodyParser = require('body-parser');
var mongoose = require(&quot;mongoose&quot;);

var app = express();

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

var api = require(&quot;../server.js&quot;);

describe(&quot;Email Module&quot;, 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(&quot;Check Email Count&quot;, function(done) {
        var body = { email: &quot;email@email.com&quot; };

        supertest(api)
            .post(&quot;/emailCount&quot;)
            .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();
            });
    });
});
</code></pre>
<hr />
<p><strong>Below is the code from file email-api.js</strong></p>
<pre class="lang-js prettyprint-override"><code>'use strict';
var express = require(&quot;express&quot;);
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;
</code></pre>
<hr />
<p><strong>Below is the code from the file server.js</strong></p>
<pre class="lang-js prettyprint-override"><code>var express = require(&quot;express&quot;);
var app = express();

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

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

app.use('/', router);

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

module.exports = app;
</code></pre>