Mocha Supertest json响应身体模式匹配问题

Dan*_*iel 13 regex api json mocha.js supertest

当我进行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();
        });
      });
    });
  });
Run Code Online (Sandbox Code Playgroud)

这是输出的图像:

在此输入图像描述

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

Dan*_*iel 6

我在理解框架的早期就提出了这个问题.对于任何偶然发现此问题的人,我建议使用chai进行断言.这有助于以更清晰的方式使用正则表达式进行模式匹配.

这是一个例子:

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


Gus*_*ira 6

您可以在测试中考虑两件事:您的 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" }
    }

}
Run Code Online (Sandbox Code Playgroud)

进而:

expect(response.body).to.be.jsonSchema({...});
Run Code Online (Sandbox Code Playgroud)

作为奖励:JSON Schema 支持正则表达式