Chai断言,无法使用should/expect来识别财产

Bip*_*o K 0 mocha.js should.js chai

您好:需要您的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.');
Run Code Online (Sandbox Code Playgroud)

使用应该

data.response.error.should.have.deep.property('#text', 'Lastname is mandatory.');
Run Code Online (Sandbox Code Playgroud)

响应JSON

{
    response: {
        error: [
            {
            '@id': '1000',
            '#text': 'Firstname is mandatory.'
            },
            {
            '@id': '10001',
            '#text': 'Lastname is mandatory.'
            }
        ],
        result: 
        {
            status: '0'
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Lou*_*uis 5

在Chai第4版之前

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

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

就像是:

data.response.should.have.deep.property("error[0].#text");
Run Code Online (Sandbox Code Playgroud)

或者,如果您使用的对象should是数组,则可以使用数组索引启动属性的路径:

data.response.error.should.have.deep.property("[0].#text");
Run Code Online (Sandbox Code Playgroud)

以下是从您显示的代码派生的完整示例:

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");
});
Run Code Online (Sandbox Code Playgroud)

柴版4及以后

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