简体   繁体   English

测试REST API-未定义主体(Node.js / Express / Mocha / Supertest)

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

I am trying to test a REST API built in Node. 我正在尝试测试Node中内置的REST API。 I have manually tested the API with Postman with no issues but I am having trouble writing the test with Mocha/Chai/Supertest. 我已经用Postman手动测试了API,没有问题,但是用Mocha / Chai / Supertest编写测试时遇到了麻烦。

When I try to test POSTing to a route the request body is undefined. 当我尝试测试POST到路由时,请求正文未定义。 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. 运行测试时,我收到错误TypeError: Cannot read property 'title' of undefined因为req.body是未定义的。 The console.log(req.body); console.log(req.body); part confirms the that req.body is undefined. 部分确认req.body未定义。

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). 首先,您需要告诉supertest您正在发送JSON类型(或其他正在发送的类型)。

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

Second, do you have a bodyParser set up in node? 其次,您是否在node中设置了bodyParser? 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 https://www.npmjs.com/package/body-parser

I too faced the same issue. 我也面临同样的问题。 I have fixed this issue by adding following line: 我通过添加以下行解决了此问题:

app.use(bodyParser.json()); app.use(bodyParser.json());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM