Monday 31 August 2020

Differences between ways to dynamically instantiate a web component

There are several ways a web component can "come to life".

Are there notable differences between the three options below?

Option 1:

const foo = document.createElement('foo-element');
document.body.appendChild(foo);

Option 2:

const div = document.createElement('div');
div.innerHTML = '<foo-element></foo-element>'
const foo = div.firstElementChild;
document.body.appendChild(foo);

Option 3:

const foo = new FooElement;
document.body.appendChild(foo);

I wrote some Unit Tests based on a Karma/Mocha stack, and created my instances with option 3.

Is this sufficient, that means, can I rely on the components having identical state/behaviour using either method, or is it necessary to repeat all my tests with all different options of instantiating applied?

One of my web components fails to be instantiated using document.createElement because of an error:

VM977:1 Uncaught DOMException: Failed to construct 'CustomElement':
The result must not have attributes
at <anonymous>:1:10

The fact that the same component can be instantiated with no problems using new tells me that, behind the curtain, there must be notable differences especially between new FooElement and document.createElement('foo-element').

I can write three general tests to test all three ways of instantiating, for sure, but is this enough?

Or should all of my existing tests be run with all 3 options of instantiating?

Or asked differently:

Is every instance exactly the same after instantiating? (assuming there is no error)



from Differences between ways to dynamically instantiate a web component

No comments:

Post a Comment