2015-01-05 4 views
1

Node로 빌드 된 REST API를 테스트하려고합니다. Postman에서 문제없이 API를 수동으로 테스트했지만 Mocha/Chai/Supertest로 테스트를 작성하는 데 문제가 있습니다.REST API 테스트 - req.body undefined (Node.js/Express/Mocha/Supertest)

경로에 대한 게시를 테스트하려고하면 요청 본문이 정의되지 않습니다. 지금까지 나의 연구에서 나는 다른 사람들과 내가하는 일과 의미있는 차이를 찾을 수없는 것 같지만, 어떤 이유로 나는 보내려하는 데이터가 전달되지 않는다. 여기

는 경로가 처리하는 방법은 다음과 같습니다

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 }); 
     }); 
    }; 

여기 내 테스트입니다 : 내가 테스트를 실행하면 req.body이 정의되어 있기 때문에

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(); 
        }); 
      }); 
    }); 

내가 오류 TypeError: Cannot read property 'title' of undefined를 얻을. console.log(req.body); 부분은 req.body가 정의되지 않았 음을 확인합니다. 여기

답변

1

두 가지 가능성 (물론, 하나의 명확한 하나의 가능성) :

먼저, 당신은 당신이 형 JSON을 보내는 (또는 당신이 보내는 어떤 다른 타입) supertest 말할 필요가있다.

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

두 번째로 노드에 bodyParser가 설정되어 있습니까? 어떤 프레임 워크를 사용하고 있는지 확실하지 않지만 내장 또는 외장 중 어떤 형태로든 신체 분석이 필요합니다. https://www.npmjs.com/package/body-parser

+0

유형을 지정하지 않은 경우 Supertest가 기본으로 'application/x-www-form-urlencoded'로 전송한다는 것을 읽었습니다. 확실하게 추가하겠습니다. bodyParser로 내 문제를 파악한 것 같습니다. 실제로 index.js 파일에이 파일을 설정했기 때문에 수동으로 테스트했을 때 API가 작동하지만 내 테스트에는 포함되지 않았습니다. 나는 이것이 이런 감독의 느낌이 들었습니다. 도와 주셔서 감사합니다! – twalters

+1

본문 파서 실마리는 이것을 이해하는 데 도움이되었습니다. –

0

나는 또한 똑같은 문제에 직면했다. 이 문제는 다음 줄을 추가하여 수정했습니다.

app.use (bodyParser.json());