Uncaught TypeError: Cannot read property 'should' of undefined

Uncaught TypeError: Cannot read property 'should' of undefined

"use strict";
import 'mocha';

let chai = require('chai');
chai.use(require('chai-json-schema'));
let chaiHttp = require('chai-http');
let should = chai.should();
chai.use(chaiHttp);

describe('Parent /search', async () => {

    it('Positive tests', function(done) {
        chai.request(server)
            .get('/search?language=en&country=ca&query=pink')
            .end(function(err: any , res: any) {
                should.equal(err, null);
                res.should.have.status(200);
                res.should.be.json;
                res.body[0].should.have.property('products');//error reading should()
                done();
            });
    });
});

------------------------GET:响应---------------- -----

{"products": [
{
"id": "2448848",
"name": "Pink 'Pink is Punk' Sweatshirt",
"seo_keyword": {
"en": "pink-pink-is-punk-sweatshirt"
},
"sku": "181476M204001",
"brand_id": 485,
"brand_name": "Valentino",
"brand_seo_keyword": "valentino",
"brand": {
"name": "Valentino",
"seo_keyword": "valentino"
},
"category_id": 208,
"category_name": "SWEATSHIRTS",
"category": {
"name": "SWEATSHIRTS",
"seo_keyword": "sweatshirts"
},
"gender": "men",
"price": {
"currency": "CAD",
"format": "$%s",
"full_format": "$%s CAD",
"regular": 760,
"sale": 403,
"discount": 47,
"country": "ca",
"display": 403
}
}

我正在尝试验证来自服务器 (GET) 的响应中的属性。我遇到了Uncaught TypeError: Cannot read property 'should' of undefined。我已经安装了 chai/mocha 的所有断言库,并将它们包含在我的文件中,但我无法找出错误。

样本中的 res.body[0] 是什么?查看您的 GET 响应(这不是有效的 JSON,我想最后应该有 ]},对吧?)我建议尝试 res.body.should.have.property('products');


要获取例如 'sku' 的产品项目,您可以执行以下操作:

const product = body.products[0];
product.should.have.property('sku').and.to.be.a('string');

由于 chai 扩充,您需要显式创建对象 Object.prototype。