Chai.js: Unveiling the Secrets of Object Containment

Chai offers a method called include. I am looking to verify if one object includes another object. Take this example:

var source = {
  name: "John",
  additionalObj: {
    type: "Sample"
  }
}

With Chai, I want to confirm that this object contains the following (which it does)

var comparison = {
  additionalObj: {
    type: "Sample"
  }
}

Attempting the following code doesn't seem to yield results:

source.should.include(comparison)

Answer №1

Hey there, I just released a new package called chai-subset. You can find it here: https://www.npmjs.org/package/chai-subset. Give it a try, it might be useful for you!

 const chai = require('chai');
 const chaiSubset = require('chai-subset');
 chai.use(chaiSubset);

 const obj = {
     a: 'b',
     c: 'd',
     e: {
         foo: 'bar',
         baz: {
             qux: 'quux'
         }
     }
 };

 expect(obj).to.containSubset({
     e: {
         foo: 'bar',
         baz: {
             qux: 'quux'
         }
     }
 });

Answer №2

The include and contain assertions have versatile uses, serving as property based language chains or methods to verify the presence of an object in an array or a substring in a string. When employed as language chains, they adjust the contain flag for the keys assertion. [emphasis added]

If you use include on an object (not an array or a string), it simply toggles the contain flag for the keys assertion. Based on your example, it might be more appropriate to test for deep equality, perhaps by checking for the key first.

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

Upon further review of other examples, this alternative approach may suit your needs better:

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

Answer №3

Chai version 4.2.0 introduces a new feature called deep include

Here are some examples from the Chai documentation:

// Deeply check if an array includes `{a: 1}`
expect([{a: 1}]).to.deep.include({a: 1});
expect([{a: 1}]).to.not.include({a: 1});

// Deeply check if an object includes `x: {a: 1}`
expect({x: {a: 1}}).to.deep.include({x: {a: 1}});
expect({x: {a: 1}}).to.not.include({x: {a: 1}});

Answer №4

One way to check the level of a subobject is by using this code:

expect(origin.otherObj).to.include(match.otherObj);

For more information, visit this link

Answer №5

If you're using Chai version 1.5.0, be sure to check out the useful method

includeDeepMembers

Visit this link for more information!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Google Apps Script to invoke a JavaScript function from an HTML file

In my Apps script project, I am working on creating a Google chart that will appear in a modal above Google Sheets. I have ChartC.html: <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> ...

Error Message: "React Routing Issue: Parameters Result in 'Cannot GET /'"

I've recently started learning React and I'm having some trouble using parameters with react-dom-router. Whenever I try to call the URL with the parameter, I keep getting a 'Cannot GET /...' Error. Here is my index.js: import React fro ...

Limit the input text to only numerical values and require a minimum length of 10 characters for phone numbers

How can I create a text box that only accepts numbers with a minimum length of 10, and another version that allows a + at the start followed by two or three sets of numbers separated by hyphens, like +91-123-456-7890? Below is the code snippet: <input ...

Is it possible to detect the source of a digest cycle in AngularJS?

I've found myself knee-deep in a legacy AngularJS project lately. The codebase is quite intricate and expansive, making it difficult to showcase here. However, I've come across an issue where functions triggered during digest changes are firing h ...

Using JavaScript to launch link in a new pop-up browser tab

Currently, I am customizing a WordPress theme and trying to add inline sharing buttons at the end of posts. However, I have encountered a roadblock in my progress. My goal is to have the link open in a new popup window using JavaScript. Below is the HTML c ...

Having difficulty navigating binary search algorithms in C programming

#include <stdio.h> int bsearch(int ar[],int n,int key) { int s=0; int e=n-1; while(s<=e){ int mid=(e+s)/2; if(mid==key){ return mid; } else if(key<mid){ e=mid-1; } ...

The react form fails to properly store user input within a formik fieldarray

I have encountered an issue with sending data from text boxes within a field array using Formik. The buttons for adding and deleting fields are working correctly, and data can be entered into the text boxes. However, when the form is submitted, the data en ...

Tips for recognizing a faulty CSS line in a WordPress site

Recently, I encountered an issue on my website, yildirimakademi, when using woocommerce to add a product to the shopping cart. While the shopping cart logo appears correctly on the right side of the navbar, I noticed that the image becomes distorted when ...

PHP/CSS Mail redirects to index.html with a message tag

I've been struggling to get this function working for some time now. I've attempted several solutions to resolve the issue, but unfortunately, I may have only exacerbated the situation. The main problem I'm facing is that upon submitting my ...

Ensuring the Line Breaks in CSS and JavaScript to Easily Modify the Style

Is there a way to determine when a line will break so I can apply different styles? The design team needs 3 buttons in a grid (3 columns) with specific sizes. They want buttons with content that breaks onto the next line to have a border-radius of 13px, w ...

What is the best way to increment the value of an input by any number using JavaScript and HTML?

My code is causing a NaN error, and I'm struggling to identify the root cause. Even providing a specific number in the addnum function did not resolve the issue. <script> var result = document.getElementById("result"); var inputVal = ...

Creating a Star Rating System Using HTML and CSS

Looking for help with implementing a Star rating Feedback on articles in Visualforce page. Came across some code that seems to fit the bill but facing issues with getting it to work when placed in a file and executed, particularly in Firefox. Any assistanc ...

No data is retrieved when using multiple filters

I am facing an issue with my getData function in the app.component.ts. It is not returning the query with all the arguments for the API Request. Strangely, I do not encounter any errors and even when trying to use console.log inside the function, it does n ...

Oops! Looks like the image property is undefined in React and causing a TypeError

Something seems to be going wrong with the Product.js file. This is where I am encountering an error related to finding the ID of the product that is being clicked on from data.js. The issue appears to be in the title section, and I'm struggling to fi ...

Can a div be relocated within another div based on a random roll of the dice?

Hey there, I'm currently working on creating a simple Monopoly-style game. As someone who is pretty new to JavaScript, I'm looking to figure out how to move the game piece around the board based on dice rolls. Any guidance or assistance would be ...

Can Sequelize be used to perform queries based on associations?

I have designed a data structure that includes an n:m relationship between "Rooms" and "Users." My current goal is to remove or delete a room. To accomplish this, I need to verify if the user initiating the deletion process is actually present in the room ...

Showing a loading screen based on the current state

I am trying to implement a loading screen component for Firebase data operations like user registration or login. I have defined the necessary indicators using useState, but the loading screen does not appear when the operation is in progress. Here is my ...

Sending a response in the catch block based on conditions

I am currently working on finding the correct method to handle a potential bad Fetch response. My goal is to immediately send a 500 response and halt the code execution if the Fetch response is not okay. However, if the response is acceptable, I need to ...

The ancient oracle of Delphi and the modern login portal of Microsoft

I need to login to a site that utilizes . To streamline the process for end-users, I want to store credentials in an .ini file and inject them into a two-stage JavaScript online prompt. Is there a way to have Delphi run a program with a browser that auto ...

The res.write function seems to be malfunctioning as it is displaying the output with HTML tags included

My endeavors in developing a web application using API's and express are met with unexpected results. The output I receive includes text mixed with HTML tags. Take a look at my code: const express = require('express'); const https = requir ...