【问题标题】:Checking the length of the array when performing tests执行测试时检查数组的长度
【发布时间】:2019-04-22 12:04:42
【问题描述】:

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

我的测试:

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

如何查看我的对象中的项目数?

【问题讨论】:

    标签: node.js testing chai


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      使用Object.keys 你可以做这样的事情,

      assert.equal(Object.keys(res.body.productDetails).length, 2);
      

      【讨论】:

        猜你喜欢
        • 2015-05-23
        • 1970-01-01
        • 1970-01-01
        • 2013-11-25
        • 1970-01-01
        • 2018-05-01
        • 2015-05-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多