执行测试时检查阵列的长度

时间:2019-04-22 12:04:42

标签: node.js testing chai

我进行测试,我需要检查对象中的项目数

我的测试:

    describe('POST /api/products/:product_id', () => {
        it(`You should receive the product with at the price of 0 ... 1000`, (done) => {
            let operationCount = productForUser.length;
            for (let i = 0; i < productForUser.length; i++) {
                chai
                    .request(server)
                    .get(`/api/products/${productForUser[i]}`)
                    .set('token', constants.userToken)
                    .end((err, res) => {
                        operationCount--;
                        expect(res).have.status(200);
                        expect(res.body).have.property('message');
                        expect(res.body.message).to.be.equal('Product found');
                        expect(res.body).have.property('productDetails');
                        expect(res.body.productDetails).to.be.a('object');
                        expect(res.body.productDetails.length).to.deep.equal(22);
                        if (operationCount == 0) {
                            done();
                        }
                    });
            }
        });
    });

我的回应

{
    "message": "Product found",
    "productDetails": {
        "product_id": 402,
        "product_name": "This is Another Bad Creation",
        "product_description": "ABC BBD the East Coast Family. Never skipped a bit while cooling on South Street. ",
        "original_price": 100,
        "sale_price": 1,
        "discount": 99,
        "creating_date": "2019-04-15T03:02:57.000Z",
        "end_date": "2019-04-25T04:00:00.000Z",
        "product_photos": [
            "https://...",
            "https://..."
        ],
        "quantity_available": 100,
        "store_id": 9,
        "categories": "Bags",
        "starting_date": "2019-04-24T23:00:00.000Z",
        "active": true,
        "merchant_name": "Silas",
        "contact_number": "+63 0927 9545228",
        "type_location": "Subic Bay Freeport",
        "likes": "0",
        "bookmarks": false,
        "is_liked": false
    }
}

我卖掉是这样做的,但是我意识到物体没有薄煎饼。

expect(res.body).have.property('productDetails');
expect(res.body.productDetails).to.be.a('object');

如何检查对象中的项目数?

2 个答案:

答案 0 :(得分:1)

您可以使用Object.keys获取对象自己的属性键的列表,并检查其长度。

Object.keys(res.body.productDetails).length

答案 1 :(得分:1)

使用Object.keys,您可以执行以下操作,

assert.equal(Object.keys(res.body.productDetails).length, 2);
相关问题