Ryan Payne
Ryan Payne

Reputation: 6301

How do I write a snapshot test for a vanilla JavaScript function?

I've written a function that adds a class to a button when clicked:

export default function () {
  const button = document.getElementById('button');
  button.addEventListener('click', ((event) => {
    event.target.classList.add('is-active');
  }));
};

I'd like to write a Jest snapshot test. But all the examples reference React. And I'm having trouble translating the examples into vanilla JavaScript.

How do I write a snapshot test for the above function?

Upvotes: 2

Views: 946

Answers (1)

Ryan Payne
Ryan Payne

Reputation: 6301

To setup, add your button to the DOM and initialize the initButton() function. Then click the button and assert on the snapshot.

import initButton from './button';

it('should add class to button when clicked', () => {
  document.body.innerHTML = '<button id="button">Click me!</button>';
  initButton();

  document.getElementById('button').click();

  expect(document.body).toMatchSnapshot();
});

The snapshot will output:

exports[`should add class to button when clicked 1`] = `
<body>
  <button
    class="is-active"
    id="button"
  >
    Click me!
  </button>
</body>
`;

Upvotes: 2

Related Questions