Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-testing-library not rendering correct snapshots

I am trying to test a component against a snapshot. The component renders a checkbox with an onChange event and its checked state is linked to the component state which is set to true.

When the snapshot is rendered, it is not displaying the onChange at all and the checked is showing as an empty string.

The outcome I want is onChange={[Function]} checked={true}.

I have tested using react-test-renderer and Enzyme and both output the snapshot correctly.

COMPONENT FILE

import React, { useState } from "react";
import "./App.css";

function App() {
    const [count, setCount] = useState(true);

    return (
        <div className="App">
            <input type="checkbox" checked={count} onChange={() => {}} />
        </div>
    );
}

export default App;

TEST FILE

import React from "react";
import App from "./App";
import { render } from "@testing-library/react";

it("renders", () => {
    const { asFragment } = render(<App />);

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

SNAPSHOT FILE

exports[renders 1] =
<DocumentFragment>
  <div
    class="App"
  >
    <input
      checked=""
      type="checkbox"
    />
  </div>
</DocumentFragment>;

expected snapshot:

exports[renders 1] = 
<DocumentFragment>
  <div
    class="App"
  >
    <input
      checked={true}
      type="checkbox"
      onChange={[Function]}
    />
  </div>
</DocumentFragment>;
like image 950
GhostNote Avatar asked Sep 20 '26 17:09

GhostNote


1 Answers

RTL is working as intended. The render method gives you back only the DOM of the component you're rendering. In the DOM the action handlers and the snapshot state are not present.

Instead of taking a snapshot a better way to test your component is to check for those values directly.

like image 161
Giorgio Polvara - Gpx Avatar answered Sep 22 '26 08:09

Giorgio Polvara - Gpx