2013-07-23 4 views
12

APIコールを行うと、返されたJSONの結果を調べたいと思います。私は身体を見ることができ、いくつかの静的データは正しくチェックされていますが、私が正規表現を使用するところはどこも壊れています。ここに私のテストの例です:Mocha Supertest jsonレスポンスボディパターンマッチングの問題

enter image description here

JSON本体の応答パターンマッチングのための正規表現を使用して上の任意のアイデア:

describe('get user', function() { 

    it('should return 204 with expected JSON', function(done) { 
     oauth.passwordToken({ 
     'username': config.username, 
     'password': config.password, 
     'client_id': config.client_id, 
     'client_secret': config.client_secret, 
     'grant_type': 'password' 
     }, function(body) { 
     request(config.api_endpoint) 
     .get('/users/me') 
     .set('authorization', 'Bearer ' + body.access_token) 
     .expect(200) 
     .expect({ 
      "id": /\d{10}/, 
      "email": "[email protected]", 
      "registered": /./, 
      "first_name": "", 
      "last_name": "" 
     }) 
     .end(function(err, res) { 
      if (err) return done(err); 
      done(); 
     }); 
     }); 
    }); 
    }); 

ここでは、出力のイメージがありますか?

+2

は、なぜあなたがしたいフィールドをつかむいない問題ではないフィールドを無視し使用します。それはあなたが正規表現で説明したものを処理することができますコールバック( 'var id = req.body.id')をチェックインし、アサーションライブラリで正規表現チェックを実行しますか? –

+1

フィールドあたりの検査も読みやすくなります。 –

答えて

5

私はフレームワークの理解の早い段階でこの質問をしました。この問題を抱えている人は、chaiを使ってアサーションをすることをお勧めします。これは、よりクリーンな方法でパターンマッチングのための正規表現の使用を助けました。私はチャイが過剰な構文を使用して考えて

res.body.should.have.property('id').and.to.be.a('number').and.to.match(/^[1-9]\d{8,}$/); 
1

:ここ

は一例です。

var assert = require('assert'); 
     //... 
     .expect(200) 
     .expect(function(res) { 
      assert(~~res.body.id); 
     }) 
     //... 
3

あなたのテストで検討することができる二つのものがあります:あなたのJSONスキーマと実際の戻り値は。あなたのJSON形式を検証するための "パターンマッチング"を実際に探している場合は、Chaiのchai-jsonスキーマ(http://chaijs.com/plugins/chai-json-schema/)を調べることをお勧めします。

これは、JSON形式をよりタイトで読みやすい方法で記述するのに役立つJSONスキーマv4(http://json-schema.org)をサポートしています。

次のように、この質問の具体的なケースでは、スキーマを使用することができます

{ 
    "type": "object", 
    "required": ["id", "email", "registered", "first_name", "last_name"] 
    "items": { 
     "id": { "type": "integer" }, 
     "email": { 
      "type": "string", 
      "pattern": "email" 
     }, 
     "registered": { 
      "type": "string", 
      "pattern": "date-time" 
     }, 
     "first_name": { "type": "string" }, 
     "last_name": { "type": "string" } 
    } 

} 

そして:

expect(response.body).to.be.jsonSchema({...}); 

そしてボーナスとしては:JSONスキーマが正規表現をサポートしています。

2

私はlodash-match-patternを書きました。これらの種類のアサーションだけを処理するのはChaiラッパーchai-match-patternです。

chai.expect(response.body).to.matchPattern({ 
    id: /\d{10}/, 
    email: "[email protected]", 
    registered: /./, 
    first_name: "", 
    last_name: "" 
}); 

や多くのいずれかがマッチャーを含め、潜在的に

chai.expect(response.body).to.matchPattern({ 
    id: "_.isInRange|1000000000|9999999999", 
    email: _.isEmail, 
    registered: _.isDateString, 
    "...": "" 
});