2016-11-09 1 views
1

REST APIのエンドポイントへの呼び出しがファイルを処理していることを検証したいと考えていますが、どうすればよいかわかりませんが、これについての例はありません。私はdocumentationを見ましたが、これは私にはあまり役に立ちませんでした。REST APIがファイルを提供するようにmocha/chaiを使用していますか?

サーバー側のコードは、基本的に(Expressで)行います

handleRetrieveContent(req, res, next) { 
    const filepaht = '...'; 
    res.sendFile(filepath) 
} 

とテストケース:

  • :私は基本的に以下のテストをやりたいと思っています

    it('Should get a file', (done) => { 
        chai.request(url) 
         .get('/api/exercise/1?token=' + token) 
         .end(function(err, res) { 
          if (err) { done(err); } 
          res.should.have.status(200); 
          // Not sure what the test here should be? 
          res.should.be.json; 
          // TODO get access to saved file and do tests on it     
         }); 
    });  
    

    応答がファイルであることを確認する

  • 有効なコンテンツ(チェックサムテスト)

助けてください。

答えて

1

提供される解決策は、さらなる実験に基づいており、答えはhttps://github.com/chaijs/chai-http/issues/126で提供されました。ノートコードはES6(ノード6.7.0でテスト済み)を前提としています。

const chai = require('chai'); 
const chaiHttp = require('chai-http'); 
const md5 = require(md5'); 
const expect = chai.expect; 

const binaryParser = function (res, cb) { 
    res.setEncoding('binary'); 
    res.data = ''; 
    res.on("data", function (chunk) { 
     res.data += chunk; 
    }); 
    res.on('end', function() { 
     cb(null, new Buffer(res.data, 'binary')); 
    }); 
}; 

it('Should get a file', (done) => { 
    chai.request(url) 
     .get('/api/exercise/1?token=' + token) 
     .buffer() 
     .parse(binaryParser) 
     .end(function(err, res) { 
      if (err) { done(err); } 
      res.should.have.status(200); 

      // Check the headers for type and size 
      res.should.have.header('content-type'); 
      res.header['content-type'].should.be.equal('application/pdf'); 
      res.should.have.header('content-length'); 
      const size = fs.statSync(filepath).size.toString(); 
      res.header['content-length'].should.be.equal(size); 

      // verify checksum     
      expect(md5(res.body)).to.equal('fa7d7e650b2cec68f302b31ba28235d8');    
     }); 
}); 

編集:これのほとんどは、可能な改善とRead response output buffer/stream with supertest/superagent on node.js serverにあった

関連する問題