断言对象的每个键都是一个数组



我有一个对象,如下API响应的结构

{
"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"
}
]
}
}

我需要为这个结构写一个单元测试

这里,如果没有数据,则数据将为{}
如果键servicescombos中没有数据,它们将不在那里,而且它们将始终是对象的数组

这就是我尝试的

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(GET/api/v1/items
OK,成功获取items:
断言错误:数据应该是Object,每个键应该是Array:预期的{Object(services,combo(},以满足上下文中的〔Function〕
。(test\items\getAllItems.js:20:17(
在processTicksAndRejections(internal/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
})   
})
})

最新更新