Search code examples
javascriptnode.jsexpressmocha.jssupertest

Testing REST API - req.body undefined (Node.js / Express / Mocha / Supertest)


I am trying to test a REST API built in Node. I have manually tested the API with Postman with no issues but I am having trouble writing the test with Mocha/Chai/Supertest.

When I try to test POSTing to a route the request body is undefined. In my research so far I can't seem to find any meaningful difference with what I am doing vs others but for some reason the data I try to send is not passed through.

Here are how the routes are handled:

    router.route('/media')
        .post(RouteController.postMedia);


    RouteController.postMedia = function(req, res) {
        var media = new Media();

        console.log(req.body);

        media.title         = req.body.title;
        media.type          = req.body.type;
        media.tags          = req.body.tags;
        media.pubdate       = req.body.pubdate;
        media.editdate      = req.body.editdate;
        media.filename      = req.body.filename;
        media.extension     = req.body.extension;
        media.description   = req.body.description;

        media.save(function(err) {
            if (err)
                res.send(err);

            res.json({ message: 'File added!', data: media });
        });
    };

Here is my test:

    var request     = require('supertest'),
        should      = require('chai').should(),
        express     = require('express'),
        mongoose    = require('mongoose'),
        app         = express();

    require('../api/routes')(app);

    var db = require('./config/db');

    describe('API Routing', function() {
        before(function(done) {
            mongoose.createConnection(db.url);
            done();
      });

        describe('Media', function () {
            it('should add new photo to database with call to POST /api/v1/media', function(done) {
                var photo = {
                    title: 'Test Photo', 
                    type: 'photo', 
                    tags: ['test', 'test2', 'asdf'], 
                    filename: 'test-photo.jpg', 
                    description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
                };

                request(app)
                    .post('/api/v1/media')
                    .send(photo)
                    .end(function(err, res) {
                        if (err) {
                            throw err
                        }

                        res.status.should.equal(200);
                        done();
                    });
            });
    });

When I run the test I get the error TypeError: Cannot read property 'title' of undefined because req.body is undefined. The console.log(req.body); part confirms the that req.body is undefined.


Solution

  • Two possibilities here (well, one definite and one possibility):

    First, you need to tell supertest you are sending type JSON (or whatever other type you are sending).

                  request(app)
                    .post('/api/v1/media')
                    .type('json')
                    .send(photo)
    

    Second, do you have a bodyParser set up in node? Not sure what framework you are using, but they all need some form of body parsing, either built-in or external. https://www.npmjs.com/package/body-parser