Search code examples
node.jsmocha.jschaisupertest

Chai - Should have Property - Supertest


Trying to check for an existence of a property and that it's not an empty string.

I can get this test to work fine:

it('the data includes a list of items', function(done){
    body.should.have.property('items').and.to.be.an('array');
    done();
});

But below, when I try to check the properties existing in the item array, I can't get it to work:

it('each item should include properties \'label\' and \'url\'', function(done){
    body['items'].should.have.property('label').and.to.be.a('string');
    body['items'].should.have.property('url').and.to.be.a('string');
    done();
});

but I get the error AssertionError: expected [ Array(3) ] to have a property 'label'

The JSON object coming back looks like this:

{
  "items": [
    {
      "label": "Item 1",
      "url": "http://www.something.com"
    },
    {
      "label": "Item 2",
      "url": "http://www.something.com"
    },
    {
      "label": "Item 3",
      "url": "http://www.something.com"
    }
  ]
}

Solution

  • try this one:

        it('each item should include properties \'label\' and \'url\'', function(done){ 
            var firstItem = body.items[0];
            firstItem.should.have.property('label').and.to.be.a('string');
            firstItem.should.have.property('url').and.to.be.a('string');
            done();
                });