Node.js 将对象的每个键断言为数组
我有一个对象,如下面的API响应结构所示。Node.js 将对象的每个键断言为数组,node.js,express,mocha.js,chai,Node.js,Express,Mocha.js,Chai,我有一个对象,如下面的API响应结构所示。 { "status": true, "message": "Successfully fetch all items!", "data": { "services": [ { "id": "E", "name": null, "price": 50, "disco
{
"status": true,
"message": "Successfully fetch all items!",
"data": {
"services": [
{
"id": "E",
"name": null,
"price": 50,
"discount_per": 2
}
],
"combos": [
{
"id": "w",
"name": "3 Times Oil change, 4 Itmes Car Wash",
"price": 5000,
"discount_per": 10,
"start_date": null,
"expiry_date": "2020-02-04T12:00:00.000Z"
}
]
}
}
我需要为此结构编写一个单元测试。这里,如果没有数据,数据将是
{}
。
如果键
服务
和组合
中没有数据,它们将不存在,而且它们将始终是对象数组这就是我所尝试的。
const expect = require('chai').expect
const request = require('supertest')
const _ = require('lodash')
const app = require('../../src/app')
describe('GET /api/v1/items', function () {
it('OK, Got items successfully', async () => {
const result = await request(app)
.get('/api/v1/items')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
expect(result)
.to.be.a('Object')
expect(result.body.status, "status should be a boolean and true")
.to.be.a('Boolean').true
expect(result.body.data, "data should be an Object and every key should an Array")
.to.satisfy(data => {
if(!_.isEmpty(data)) {
expect(data).to.have.any.keys('services', 'combos')
_.forOwn(data, (value, key) => {
expect(data[key]).to.be.a('Array')
})
}
})
})
})
但我的错误率正在下降。1) 获取/api/v1/items
好,已成功获取项目:
AssertionError:数据应该是一个对象,每个键都应该是一个数组:需要{Object(services,combos)}来满足[Function]
在上下文中。(test\items\getAllItems.js:20:17)
在处理和拒绝时(内部/process/task_queues.js:94:5)
我把它修好了,这是一个愚蠢的错误,我没有注意到。我没有从满足函数返回任何内容。
describe('GET /api/v1/items', function () {
it('OK, Got items successfully', async () => {
const result = await request(app)
.get('/api/v1/items')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
expect(result)
.to.be.a('Object')
expect(result.body.status, "status should be a boolean and true")
.to.be.a('Boolean').true
expect(result.body.data, "data should be an Object and every key should an Array")
.to.satisfy(data => {
expect(data).to.be.a('Object')
if(!_.isEmpty(data)) {
expect(data).to.have.any.keys('services', 'combos')
_.forOwn(data, (value, key) => {
expect(data[key]).to.be.a('Array')
})
return true
}
return true
})
})
})