0

Hello: Need your help on a chai assertion.

I have a JSON response as shown below. I want to assert that it contains "Lastname is mandatory" only.

I tried using this statement but the error i get is AssertionError: expected [ Array(2) ] to have a deep property '#text'. Please help how to write this correctly.

using expect

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

using should

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

Response JSON

{
    response: {
        error: [
            {
            '@id': '1000',
            '#text': 'Firstname is mandatory.'
            },
            {
            '@id': '10001',
            '#text': 'Lastname is mandatory.'
            }
        ],
        result: 
        {
            status: '0'
        }
    }
}
Bipo K
  • 395
  • 3
  • 20

2 Answers2

6

Prior to Chai version 4

The use of deep with property requires that you pass a complete path to the property you want to test. In other words, deep.property won't do a search through all the properties for you. As the documentation puts it:

If the deep flag is set, you can use dot- and bracket-notation for deep references into objects and arrays.

Something like:

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

Or you can start the path to the property with an array index if the object on which you use should is an array:

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

Here is a complete example derived from the code you show:

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 version 4 and later

The OP was using a release of Chai earlier than version 4. If you are using Chai version 4 and over, the flag to use to is not .deep anymore but .nested. So in earlier versions where you would use data.response.should.have.deep.property("error[0].#text"); in version 4 or later you'd use data.response.should.have.nested.property("error[0].#text");

Louis
  • 146,715
  • 28
  • 274
  • 320
0

Thanks to answer from @shvaikalesh at github. It has the relevant answer to my question which i provide here for future reference + the code extract is also below for quick reference.

chai.expect(data.response.error.some(e => e['#text'] == 'Lastname is mandatory.')).to.be.true
Bipo K
  • 395
  • 3
  • 20