比较断言中的函数输出类型 [英] Comparing the function output type in assertion

查看:128
本文介绍了比较断言中的函数输出类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力使用chai,mocha和JS-DOM编写测试断言. 我有一个简单的功能,如:

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);
}

在我进行的测试中:

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

但错误:

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 ?

推荐答案

以下是 ul.element是一个JavaScript对象.更确切地说,它是一个DOM节点.但是,<ul></ul>是一个字符串.柴用===进行比较.如果将DOM节点与使用===进行比较,则唯一会返回true值的是完全相同的DOM节点. 完全相同"表示完全相同的JavaScript对象.如果您这样做:

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

您将在控制台上找到true.如果您这样做:

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

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

之所以得到false,是因为两个操作数是两个不同的对象.为了您的目的,两个DOM节点可能相同",但是就===而言,它们是不同的.由于没有字符串可以是与DOM节点相同的对象,因此您的测试将失败.该错误消息可能看起来令人困惑,但这是因为当JSDOM打印出错误时,它会序列化DOM节点.也就是说,然后JSDOM打印出DOM节点,它实际上打印出其.outerHTML属性的值,而.outerHTML是该节点的序列化.

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.

您要测试的内容取决于您的最终目标.如果要测试元素的结构,可以检查.outerHTML,类似:

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>");

您的测试标题是应该具有addClass方法" ...所以也许您应该对此进行测试:

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");

如果您打算用它作为测试来获得HTMLElement的代理,我建议改为这样做:

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

这篇关于比较断言中的函数输出类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆