user2997932
user2997932

Reputation: 127

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.

Upvotes: 3

Views: 1137

Answers (1)

Daniel
Daniel

Reputation: 311

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();
});

Upvotes: 1

Related Questions