1

I am using react-testing-library in my app and I am trying to use snapshot-diff for snapshot difference testing. Essentially what I need to do is to generate snapshot before and after user action. and pass it to toMatchDiffSnapshot method. But if I pass container, it exactly the same as before user action. How can I get updated html structure in react testing library render method after user actions? I tried screen as well, didn't work

it('has clear button after typing', async () => {
  const { container } = render(<SearchBar />)
  expect(container).toMatchSnapshot()

  await userEvent.type(screen.getByRole('textbox'), 'JavaScript')
  const updatedContainer = screen
  expect(container).toMatchDiffSnapshot(updatedContainer)
})

with react-test-renderer it would like in example below. But I want to avoid install extra package

import renderer from 'react-test-renderer';
import { toMatchDiffSnapshot } from 'snapshot-diff';

expect.extend({ toMatchDiffSnapshot });

import App from './App';

describe('App', () => {
  it('increments the counter', () => {
    const component = renderer.create(<App />);
    const tree = component.toJSON();
    expect(tree).toMatchSnapshot();

    component.root.findAllByType('button')[0].props.onClick();

    const treeUpdate = component.toJSON();
    expect(tree).toMatchDiffSnapshot(treeUpdate);
  });
});

1 Answers1

1

If you're trying to test the updated HTML structure of a React component after a user action, you can use the rerender function:


it('has clear button after typing', async () => {
  const { container, rerender } = render(<SearchBar />)
  expect(container).toMatchSnapshot()

  await userEvent.type(screen.getByRole('textbox'), 'JavaScript')

  // The magic
  rerender(<SearchBar />)
  expect(container).toMatchDiffSnapshot()
});

It's important to note that re-rendering the component may cause the component to lose its state and props, so you may need to use additional techniques to preserve the state and props of the component.

Good luck!

bybruno
  • 41
  • 3