如何使用Chai深度解析JSON API输出?
JSON API输出:
{
"data": {
"id": "87zc08spyq69",
"type": "data-collector",
"attributes": {
"sensors": [
{
"metadata": {
"sensor_id": 837490,
"unit": "m",
"unit_description": "meters",
"datum": "WGS84",
"offset": -0.001
},
"data": [
{
"time": "2017-12-31T23:59:59Z",
"value": "14.9",
"quality": 4
},
{
"time": "2017-12-31T22:59:59Z",
"value": "12",
"quality": 1
},
{
"time": "2017-12-31T21:59:59Z",
"value": "10",
"quality": 2
}
]
}
]
}
},
"links": {
"self": "/locations/87zc08spyq69/counter/time-series"
}
}
工作到目前为止:
const chai = require('chai');
const should = chai.should();
const chaiHttp = require('chai-http');
const chaiThings = require('chai-things');
chai.use(chaiHttp);
chai.use(chaiThings);
uri = '/locations/87zc08spyq69/counter/time-series';
describe('/GET', () => {
it('should get location counter in time-series', done => {
chai.request(server)
.get(uri)
.set('Content-Type', "application/vnd.api+json")
.set('Accept', "application/vnd.api+json")
.end((err, res) => {
if (err) {
console.error(err);
done(err,null);
}
should.not.exist(err);
res.status.should.eql(200);
res.type.should.eql("application/vnd.api+json");
res.body.should.have.property('data').has.property('attributes')
.has.property('sensors')
.to.be.an('array')
.should.contain.an('object');
res.body.should.have.property('links').has.property('self').to.be.eql(uri);
done();
});
});
});
我无法测试以下数组的任何部分:
"data": [
{
"time": "2017-12-31T23:59:59Z",
"value": "14.9",
"quality": 4
},
{
"time": "2017-12-31T22:59:59Z",
"value": "12",
"quality": 1
},
{
"time": "2017-12-31T21:59:59Z",
"value": "10",
"quality": 2
}
]
我已经尝试过将东西带到深处"测试"数据","数据/时间","数据/值"但我一直都有错误。
如何测试传感器/数据,传感器/数据/时间,传感器/数据/值?
提前感谢您的帮助
答案 0 :(得分:1)
它非常丑陋,可能有更好的方法,但这对我有用
res.body.should.have.property('data').have.property('attributes')
.have.property('sensors')
.have.deep.property('[0].data').have.deep.property('[0].time').eql("2017-12-31T23:59:59Z");