open-wc / open-wc

Open Web Components: guides, tools and libraries for developing web components.
https://open-wc.org/
MIT License
2.28k stars 425 forks source link

[testing] overwrite chai `displayed` property so it works with elements in the Shadow DOM #2583

Open jpzwarte opened 1 year ago

jpzwarte commented 1 year ago

So the existing displayed property of chai-dom doesn't work when the element is inside the Shadow DOM.

The workaround for that is to use getRootNode to check if the element is inside the document:

import chai from '@esm-bundle/chai';

const plugin: Chai.ChaiPlugin = function (chai, utils) {
  utils.overwriteProperty(chai.Assertion.prototype, 'displayed', function () {
    return function () {
      const el = utils.flag(this, 'object') as HTMLElement,
        actual =
          el.getRootNode({ composed: true }) === document ? window.getComputedStyle(el).display : el.style.display;

      this.assert(
        actual !== 'none',
        `expected ${el.toString()} to be displayed, but it was not`,
        `expected ${el.toString()} to not be displayed, but it was as ${actual}`,
        actual
      );
    };
  });
};

chai.use(plugin);

What is easier? Should I try and get this fixed upstream and then update the chai-dom version here? Or patch the displayed property here?

jpzwarte commented 1 year ago

Created a PR for this in chai-dom: https://github.com/nathanboktae/chai-dom/pull/64

jpzwarte commented 1 year ago

Yay for small victories. The PR in chai-dom got merged! Do we have to wait for a new release of chai-dom or @esm-bundle/chai? Not sure what the process is.