harryg
harryg

Reputation: 24077

Testing value of nested property in chai-as-promised and mocha

I'm trying to test a function that returns a promise using the chai-as-promised library. The result in my promise is an object with nested properties. Is it possible to test a deeply nested property's value.

E.g.

function myFunc() {
  return new Promise((resolve, reject) => {
    const data = {
      thing: {
        foo: 'bar',
        baz: 'lah'
      }
    }
    resolve(data)
  })
}

How can I test that the foo property equals "bar" without checking the entire object? I've tried something like this:

expect(myFunc()).to.eventually.have.property('thing.foo', 'bar')

But no luck!

Upvotes: 7

Views: 5107

Answers (1)

Quentin Roy
Quentin Roy

Reputation: 7887

Using deep property lookup should work. Just add the deep keyword before property.

expect(myFunc()).to.eventually.have.deep.property('thing.foo', 'bar')

If you prefer the verbose way, you should also be able to do stuff like:

expect(myFunc())
   .to.eventually.have.property('thing')
   .that.has.property('foo')
   .that.is.equal.to('bar');

Upvotes: 12

Related Questions