Regex Mocha Supertest json响应主体模式匹配问题
当我调用API时,我想检查返回的JSON的结果。我可以看到主体和一些静态数据被正确地检查,但是无论我在哪里使用正则表达式,都会出现问题。以下是我的测试示例:Regex Mocha Supertest json响应主体模式匹配问题,regex,json,api,mocha.js,supertest,Regex,Json,Api,Mocha.js,Supertest,当我调用API时,我想检查返回的JSON的结果。我可以看到主体和一些静态数据被正确地检查,但是无论我在哪里使用正则表达式,都会出现问题。以下是我的测试示例: describe('get user', function() { it('should return 204 with expected JSON', function(done) { oauth.passwordToken({ 'username': config.username,
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主体响应的模式有什么想法吗?我在理解框架的早期就提出了这个问题。对于任何一个偶然发现这一点的人,我建议使用chai作为断言。这有助于以更干净的方式使用正则表达式进行模式匹配 以下是一个例子:
res.body.should.have.property('id').and.to.be.a('number').and.to.match(/^[1-9]\d{8,}$/);
我认为柴使用了过多的语法。
<> P>您可以在测试中考虑两件事情:JSON模式和实际返回值。如果您真的在寻找“模式匹配”来验证JSON格式,那么看看Chai的Chai JSON模式()可能是个好主意 它支持JSON模式v4(),这将帮助您以更紧凑和可读的方式描述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模式支持正则表达式我写的,它可以处理这些类型的断言。它可以处理您用正则表达式描述的内容:
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,
"...": ""
});
为什么不在回调(
var id=req.body.id
)中获取要检查的字段,并使用断言库运行正则表达式检查呢?每个字段的检查也更具可读性。
chai.expect(response.body).to.matchPattern({
id: "_.isInRange|1000000000|9999999999",
email: _.isEmail,
registered: _.isDateString,
"...": ""
});