1

I create a component with useId as follows:

function Form() {
  const id = useId();

  return (
    <div>
      <label htmlFor={id}>name</label>
      <input id={id} />
    </div>
  );
}

When I ran a snapshot test, I got a snapshot like the following. As you see, the ID of the DOM node is ":r1:".

The test is like follows:

import { render } from '@testing-library/react';

describe('Snapshot', () => {
  test('default', () => {
    const { asFragment } = render(<Form />);

    expect(asFragment()).toMatchSnapshot();
  });
});

The snapshot is like follows:

exports[`snapshot 1`] = `
<DocumentFragment>
  <div>
    <label
      for=":r1:"
    >
      name
    </label>
    <input
      id=":r1:"
    />
  </div>
</DocumentFragment>
`;

If I add other tests, the snapshot test can fail because the DOM node may get a different ID, like ":r2:", ":r3:" and so on.

Is there a way to create robust snapshot tests for a component with useId?

I tried to make a mock for useId like following. It actually works.

let id = 0;

beforeEach(() => {
  id = 0;
});

const generateId = () => ++id;

jest.mock('react', () => ({
  ...jest.requireActual('react'),
  useId: generateId,
}));

I understand that useId just generates unique IDs, but doesn't imply that the same IDs will be expected when used in the same way. So I think we should not expect useId to return the same ID in normal usage. With this mock, useId generates independent IDs for each test and the ID sequence it generates is always constant.


If you know of a better way, I'd be glad to know!

0 Answers0