Comparing the function output type in assertion

拈花ヽ惹草 提交于 2019-12-24 05:09:08

问题


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) ? el :document.createElement(el);
}

in the tests I have:

it('should have addClass method', function () {
  const ul = (new HtmlElement('ul'));
  ul.element.should.be.equals('<ul></ul>'); // Outputs the actual UL 
});

but the error:

AssertionError: expected <ul></ul> to equal '<ul></ul>'

is the one I can't understand - what type of the output is returned and what assertion should be used here ?


回答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);


来源:https://stackoverflow.com/questions/54706993/comparing-the-function-output-type-in-assertion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!