Search code examples
javascriptwebcomponentsjestjs

web components snapshot test


Given this custom component:

const style = `
  div {
    color: red;
  }
`;

const html = `
  <div>
    SAMPLE WEB COMPONENT
  </div>
`;

const $element = document.createElement('template');
$element.innerHTML = `
  <style>
    ${style}
  </style>
  ${html}
`;

export default class Sample extends HTMLElement {
  constructor() {
    super();
    this.root = this.attachShadow({ mode: 'closed' });
    this.root.appendChild($element.content.cloneNode(true));
  }
}

Is there any chance of having snapshot tests using Jest? Using something like jest-snapshot-serializer-raw or jsdom + serializer or other.


Solution

  • I had the same question and all it took was getting the WebComponent in a serialized way (innerHTML) and checking the snapshot on that:

    it('should render correctly', () => {
        const myComponent = new MyComponent();
    
        expect(myComponent.innerHTML).toMatchSnapshot();
    });