Mocha Supertest json response body pattern matching issue

Daniel picture Daniel · Jul 24, 2013 · Viewed 8.6k times · Source

When I make an API call I want to inspect the returned JSON for its results. I can see the body and some the static data is being checked properly, but wherever I use regular expression things are broken. Here is an example of my test:

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

Here is an image of the output:

enter image description here

Any ideas on using regular expression for pattern matching the json body response?

Answer

Daniel picture Daniel · Oct 4, 2013

I asked this question early in my understanding of the framework. For anyone else who stumbles on this, I recommend using chai for assertion. This helped use regular expression for pattern matching in a much cleaner way.

Here is an example:

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