【问题标题】:Chai assertion, unable to identify property using should / expectChai 断言,无法使用应该/期望来识别属性
【发布时间】:2017-10-02 21:38:41
【问题描述】:

您好:在chai 断言方面需要您的帮助。

我有一个如下所示的 JSON 响应。我想断言它只包含“姓氏是强制性的”。

我尝试使用此语句,但我得到的错误是AssertionError: expected [ Array(2) ] to have a deep property '#text'。请帮助如何正确编写此内容。

使用期望

chai.expect(data.response.error).to.have.deep.property('#text', 'Lastname is mandatory.');

使用应该

data.response.error.should.have.deep.property('#text', 'Lastname is mandatory.');

响应 JSON

{
    response: {
        error: [
            {
            '@id': '1000',
            '#text': 'Firstname is mandatory.'
            },
            {
            '@id': '10001',
            '#text': 'Lastname is mandatory.'
            }
        ],
        result: 
        {
            status: '0'
        }
    }
}

【问题讨论】:

    标签: mocha.js chai should.js


    【解决方案1】:

    Chai 4 之前的版本

    deepproperty 的使用要求您将完整路径传递给要测试的属性。换句话说,deep.property 不会为您搜索所有属性。正如documentation 所说:

    如果设置了deep 标志,您可以使用点和括号表示法对对象和数组进行深度引用。

    类似:

    data.response.should.have.deep.property("error[0].#text");
    

    或者,如果您使用should 的对象是一个数组,您可以使用数组索引开始属性的路径:

    data.response.error.should.have.deep.property("[0].#text");
    

    这是从您展示的代码派生的完整示例:

    const chai = require("chai");
    chai.should();
    
    const data = {
        response: {
            error: [
                {
                '@id': '1000',
                '#text': 'Firstname is mandatory.'
                },
                {
                '@id': '10001',
                '#text': 'Lastname is mandatory.'
                }
            ],
            result:
            {
                status: '0'
            }
        }
    };
    
    it("works", () => {
        data.response.should.have.deep.property("error[0].#text");
        // Or this, which looks weird but is allowed...
        data.response.error.should.have.deep.property("[0].#text");
    });
    

    Chai 版本 4 及更高版本

    OP 使用的是早于版本 4 的 Chai 版本。如果您使用的是 Chai 版本 4 及更高版本,则要使用的标志不再是 .deep,而是 .nested。因此,在早期版本中,您将在版本 4 或更高版本中使用 data.response.should.have.deep.property("error[0].#text");,您将使用 data.response.should.have.nested.property("error[0].#text");

    【讨论】:

    • 非常感谢您提供详细信息。
    【解决方案2】:

    感谢@shvaikalesh 在github 的回答。它有我的问题的相关答案,我提供here 以供将来参考 + 代码摘录也在下面以供快速参考。

    chai.expect(data.response.error.some(e => e['#text'] == 'Lastname is mandatory.')).to.be.true
    

    【讨论】:

      猜你喜欢
      • 2012-07-16
      • 2017-03-04
      • 1970-01-01
      • 2022-01-23
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2013-03-12
      • 2020-02-24
      相关资源
      最近更新 更多