16

当我进行 API 调用时,我想检查返回的 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": "qa_test+apitest@example.com",
          "registered": /./,
          "first_name": "",
          "last_name": ""
        })
        .end(function(err, res) {
          if (err) return done(err);
          done();
        });
      });
    });
  });

这是输出的图像:

在此处输入图像描述

关于使用正则表达式进行模式匹配 json 正文响应的任何想法?

4

4 回答 4

7

您可以在测试中考虑两件事:您的 JSON 模式和实际返回的值。如果您真的在寻找“模式匹配”来验证您的 JSON 格式,那么看看 Chai 的 chai-json-schema ( http://chaijs.com/plugins/chai-json-schema ) 可能是个好主意/)。

它支持 JSON Schema v4 ( http://json-schema.org ),这将帮助您以更紧凑和可读的方式描述您的 JSON 格式。

在这个问题的特定情况下,您可以使用如下模式:

{
    "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 模式支持正则表达式

于 2016-05-06T11:56:14.790 回答
6

我在理解框架的早期就问过这个问题。对于任何偶然发现这一点的人,我建议使用 chai 进行断言。这有助于以更简洁的方式使用正则表达式进行模式匹配。

这是一个例子:

res.body.should.have.property('id').and.to.be.a('number').and.to.match(/^[1-9]\d{8,}$/);
于 2013-10-04T18:12:45.573 回答
4

我写了lodash-match-pattern,它是 Chai 包装器chai-match-pattern来处理这些类型的断言。它可以处理您使用正则表达式描述的内容:

chai.expect(response.body).to.matchPattern({
  id: /\d{10}/,
  email: "qa_test+apitest@example.com",
  registered: /./,
  first_name: "",
  last_name: ""
});

或使用许多包含的匹配器中的任何一个,并可能忽略无关紧要的字段

chai.expect(response.body).to.matchPattern({
  id: "_.isInRange|1000000000|9999999999",
  email: _.isEmail,
  registered: _.isDateString,
  "...": ""
});
于 2016-11-15T21:57:55.750 回答
0

我认为 chai 使用了过于冗长的语法。

var assert = require('assert');
        //...
        .expect(200)
        .expect(function(res) {
            assert(~~res.body.id);
        })
        //...
于 2015-04-29T12:46:48.883 回答