Search code examples
javascripttypescriptmocha.jsweb-componentjsdom

Mocha Webcomponents testing - ReferenceError: customElements is not defined


I'm trying to do some very basic webcoponnets testing using typescript and mocha. I'm using jsdom to mock out the basic documents global, so I have --require jsdom-global/register in my moch opts.

Here is my test:

import { assert } from "chai";

class WordCount extends HTMLParagraphElement {
  constructor() {
    super();
  }
}

describe("simple test", () => {
    it("works", () => {
      customElements.define('word-count', WordCount, { extends: 'p' });
      assert.isOk(true);
    });
});

But I get the following error:

ReferenceError: customElements is not defined

The latest version of JSDom (which I'm using) supports customElements. I think the issue boils down to window.customElements vs customElements. The former syntax works, but the code I'm trying to test uses the latter syntax. What's the difference?


Solution

  • In the browser context, there's not difference between window.customElements and customElements because window is the default namespace for the variables defined globally.

    var my_var = 'foo"
    console.log( window.my_var ) //foo
    console.log( window.customElement === customElement )
    

    The test JSDoc library is executed in the Node.js context, which is not a browser and therefore won't expose window as its global / default namespace.

    However JSDoc exposes a simulated browser context through a window property. So you can use window.customElements() and there's no difference with the code you trying to test.