Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asserting object equality in Javascript test (chai)

I need to assert equality between two points in my JavaScript unit tests:

var pnt1 = {x: 2, y: 3};

and

var pnt2 = {x: 2, y: 3};

When I do

assert.equal(pnt1, pnt2);

It says the points are different. Can I exclude from the check the fact that the objects are different instances (so in fact they are "not equal")?

I'd like to avoid creating a list of assert, one for each field to test (in this case .x and .y)

like image 508
Gianluca Ghettini Avatar asked Nov 26 '15 10:11

Gianluca Ghettini


People also ask

How do you assert chai?

var assert = require('chai'). assert , foo = 'bar' , beverages = { tea: [ 'chai', 'matcha', 'oolong' ] }; assert. typeOf(foo, 'string'); // without optional message assert. typeOf(foo, 'string', 'foo is a string'); // with optional message assert.

What is deep equal in Chai?

When you use equal , Chai uses a === comparision. So when comparing objects, Chai will check for reference. When you use deepEqual , Chai will go down the object hierarchy and compare every value of every property. Example: const a = {"a": "a"}; const b = {"a": "a"}; expect(a).

What assertion styles are present in Chai testing assertion library?

Chai is such an assertion library, which provides certain interfaces to implement assertions for any JavaScript-based framework. Chai's interfaces are broadly classified into two: TDD styles and BDD styles.

What is assert deepEqual?

The assert. deepEqual() method tests if two objects, and their child objects, are equal, using the == operator. If the two objects are not equal, an assertion failure is being caused, and the program is terminated. To compare the objects using the === operator, use the assert.


1 Answers

Instead of .equal, use .deepEqual:

assert.deepEqual(pnt1, pnt2);

This will perform a deep comparison instead of simply checking for equality.

like image 181
Cerbrus Avatar answered Sep 24 '22 23:09

Cerbrus