WebReflection/document-register-element

"Cannot read property 'create' of undefined" when not registering a class as a custom element

Lukas-Kullmann opened this issue · 1 comments

When I use this polyfill to use custom elements, I am not able to create a new CustomElement() if I did not add it to the customElements-registry beforehand.

The usecase at which I discovered this was in a test, where I wanted to test some functionality, that was not really dependent on the element being registered as a custom element. So I went like

describe('test suite name', () => {
    let element: HTMLElement;

    beforeEach(() => {
        class Base extends HTMLElement { }

        element = new Base();
    });

    it('test name', () => {
        // some test
    });
});

(I used typescript syntax here and compiled it down to ES5, but that is not the point here)

The problem that arose here was now, that "Cannot read property 'create' of undefined".
This was triggered by this line. The problem here was, that info is undefined since the element was not registered as a custom element.

My workaround was the following:

describe('test suite name', () => {
    let element: HTMLElement;
    let BaseClass: new(...args: any[]) => HTMLElement;

    beforeAll(() => {
        class Base extends HTMLElement { }

        customElements.define('some-very-unique-name', Base);

        BaseClass = Base;
    });

    beforeEach(() => {
        element = new BaseClass();
    });

    it('test name', () => {
        // some test
    });
});

Is this intended behavior? I would prefer not to being forced to add this element as a custom element in this test, since it is really not needed and I might reuse the name in another test and be screwed then, since you cannot define the name twice.

You cannot invoke HTMLElement super constructor if your class is not registered.

Try this in any browser with native support:

class MyEl extends HTMLElement {}
new MyEl

Read the error.

This is not a polyfill issue, this is how the specification works.