Search code examples
javascriptarraysobjecttddchai

Chai.js: Object contains/includes


Chai has an include method. I want to test to see if an object contains another object. For example:

var origin = {
  name: "John",
  otherObj: {
    title: "Example"
  }
}

I want to use Chai to test if this object contains the following (which it does)

var match = {
  otherObj: {
    title: "Example"
  }
}

Doing this does not appear to work:

origin.should.include(match)

Solution

  • The include and contain assertions can be used as either property based language chains or as methods to assert the inclusion of an object in an array or a substring in a string. When used as language chains, they toggle the contain flag for the keys assertion. [emphasis mine]

    So if you're invoking include on an object (not an array or a string), then it only serves to toggle the contain flag for the keys assertion. By the looks of your example, testing for deep equality would make more sense, possibly checking for the key first.

    origins.should.include.keys("otherObj");
    origins.otherObj.should.deep.equal(match.otherObj);
    

    Actually, now I browse the other examples, you would probably be happiest with this :

    origins.should.have.deep.property("otherObj", match.otherObj)