React-Testing-Library - создание снимка ПОСЛЕ fireEvent - PullRequest
0 голосов
/ 07 мая 2019

У меня проблемы с созданием снимка после вызова fireEvent.focus().

Вот тест. У меня есть два теста: 1, который сравнивает снимок до фокусировки ввода, и 1, который сравнивает снимок после фокусировки ввода.

describe("Unit: <OutlinedInput />", (): void => {

  describe("Initial render", (): void => {
    describe("renders as snapshot", (): void => {
      it("for standard fields", (): void => {
        const { asFragment } = render(<OutlinedInput {...standardProps} />, {});
        expect(asFragment()).toMatchSnapshot();
      });
    });
  });

  describe("On focus in, no input", (): void => {
    describe("renders as snapshot", (): void => {
      it("for standard fields", (): void => {
        const { getByLabelText, container, asFragment } = render(
          <OutlinedInput {...standardProps} />,
          {}
        );
        const input = getByLabelText(standardProps.label);
        fireEvent.focus(input);
        waitForDomChange(container)
          .then(
            (): void => {
              expect(asFragment()).toMatchSnapshot();
            }
          )
          .catch((error: Error): void => console.log(error.message));
      });
    });
  });
});

Однако, когда я проверяю снимок, создается только 1:

exports[`Unit: <OutlinedInput /> Initial render renders as snapshot for standard fields 1`] = `
<DocumentFragment>
  <div
    class="MuiFormControl-root MuiFormControl-marginDense MuiFormControl-fullWidth"
    data-testid="outlinedInputFormControl"
  >
    <label
      class="MuiFormLabel-root MuiInputLabel-root MuiInputLabel-formControl MuiInputLabel-animated MuiInputLabel-marginDense MuiInputLabel-outlined"
      data-shrink="false"
      data-testid="outlinedInputLabel"
      for="name"
    >
      Name Label
    </label>
    <div
      class="MuiInputBase-root MuiOutlinedInput-root MuiInputBase-formControl MuiInputBase-marginDense"
      data-testid="outlinedInputInput"
    >
      <fieldset
        aria-hidden="true"
        class="PrivateNotchedOutline-root-62 MuiOutlinedInput-notchedOutline makeStyles-notchedOutline-6"
        style="padding-left: 8px;"
      >
        <legend
          class="PrivateNotchedOutline-legend-63"
          style="width: 0.01px;"
        >
          <span>
            ​
          </span>
        </legend>
      </fieldset>
      <input
        aria-invalid="false"
        class="MuiInputBase-input MuiOutlinedInput-input MuiInputBase-inputMarginDense MuiOutlinedInput-inputMarginDense"
        id="name"
        type="string"
        value=""
      />
    </div>
  </div>
</DocumentFragment>
`;

Похоже, что asFragment был создан во время первоначального рендеринга компонента и не обновляется fireEvent.focus(input). Это делает оба снимка идентичными, и я предполагаю, что React-Testing-Library создает только снимок 1 из-за этого.

Что должно произойти, если созданы 2 снимка. Один для второго теста (который имеет fireEvent.focus(input)) должен иметь разные классы для различных компонентов. Например, элемент <label> должен иметь дополнительный класс Mui-Focused, и я вижу, что происходит, когда я запускаю свое приложение в браузере.

Как мне это исправить?

1 Ответ

0 голосов
/ 07 мая 2019

Я получил его на работу.По-видимому, вы не должны ждать обновления DOM, прежде чем сравнивать снимок.

Это изменение сделано:

  describe("On focus in, no input", (): void => {
    describe("renders as snapshot", (): void => {
      it("for standard fields", (): void => {
        const { getByLabelText, asFragment } = render(
          <OutlinedInput {...standardProps} />,
          {}
        );
        const input = getByLabelText(standardProps.label);
        fireEvent.focus(input);
        expect(asFragment()).toMatchSnapshot();
      });
    });
  });

...