如何检查JavaScript对象是否是新的DOM元素?

时间:2018-05-07 03:36:34

标签: javascript html qunit google-blockly

我有一个功能

mutationToDom: function() {
    var container = document.createElement( 'mutation' );

    container.setAttribute( 'string', 'test' );

    return container;
}

容器为<mutation string="test"></mutation>

我在单元测试中调用此函数后如何检查?

QUnit.test( 'check function mutationToDom', function( assert ) {
    var container = testBlock.mutationToDom();
    assert.ok( container === ???, 'mutation is created with correct value' );
});

尝试#1

我尝试使用XMLSerializer()将XML转换为字符串

var containerString = new XMLSerializer().serializeToString(container);

但是,containerString

"<mutation xmlns="http://www.w3.org/1999/xhtml" string="test"></mutation>"

而不是"<mutation string="test"></mutation>"

2 个答案:

答案 0 :(得分:2)

如何检查outerHTML

var testBlock = {
  mutationToDom: function() {
    var container = document.createElement('mutation');
    container.setAttribute('string', 'test');
    return container;
  }
};

QUnit.test( 'check function mutationToDom', function( assert ) {
    var container = testBlock.mutationToDom();
    assert.ok( container.outerHTML === '<mutation string="test"></mutation>', 'mutation is created with correct value' );
});
<link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.6.0.css">
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="https://code.jquery.com/qunit/qunit-2.6.0.js"></script>

答案 1 :(得分:0)

要回答标题中的具体问题,请尝试testObject instanceof Element...HTMLElement?这可能是检查.outerHTML的前提条件,如31piy所示。