gpt4 book ai didi

Chai 测试 JSON API 输出

转载 作者:行者123 更新时间:2023-12-04 13:03:32 25 4
gpt4 key购买 nike

如何使用 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
}
]

我曾尝试使用 chai-things 来“深入”测试“数据”、“数据/时间”、“数据/值”,但我不断收到错误消息。

如何测试传感器/数据、传感器/数据/时间、传感器/数据/值?

在此先感谢您的帮助

最佳答案

它非常丑陋,可能有更好的方法来做到这一点,但这对我有用

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");

关于Chai 测试 JSON API 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46575524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com