Skip to content Skip to sidebar Skip to footer

Comparing The Function Output Type In Assertion

I'm struggling with writing a test assertion using chai, mocha, and JS-DOM. I have a simple function like: function HtmlElement(el) { this.element = (el instanceof HTMLElement)

Solution 1:

Here's what deceze meant in his comment. In the test:

ul.element.should.be.equals('<ul></ul>');

ul.element is a JavaScript object. More precisely, it is a DOM node. However, <ul></ul> is a string. Chai does the comparison with ===. If you compare a DOM node with something using ===, the only thing that will return a true value is the exact same DOM node. "Exact same" means exact same JavaScript object. If you do:

const node = document.createElement("ul");
console.log(node === node);

You get true on the console. If you do this:

console.log(document.createElement("ul") === document.createElement("ul"));

You get false because the two operands are two different objects. For your purposes, the two DOM nodes may be "the same" but they are not the same as far as === is concerned. Since no string can be the same object as a DOM node, then your test fails. The error message may seem confusing, but that's because when JSDOM prints out the error, it serializes the DOM node. That is, then JSDOM prints out the DOM node, it really prints out the value of its .outerHTML property, and .outerHTML is the serialization of the node.

What you want to test for depends on what your ultimate aim is. If you want to test the structure of the element, you could check .outerHTML, something like:

ul.element.should.have.property("outerHTML").equal("<ul></ul>");

The title of your test is "should have addClass method"... so maybe you should be testing this:

ul.element.should.have.property("addClass").be.a("function");

If you meant to have that be a proxy for testing that you get an HTMLElement, I'd suggest doing this instead:

ul.element.should.be.instanceof(HTMLElement);

Post a Comment for "Comparing The Function Output Type In Assertion"