Writing a generic snapshot test

Talking about writing tests is one thing, but let's actually start implementing our tests. I typically approach test-writing in the following way:

  • Write a generic snapshot test
  • Write some subcomponent-specific tests
  • Check content
  • Check interactions

Snapshot tests can be used to verify initial state renders and renders after specific conditions are met. This works by grabbing a representation of your component, storing that, and then using it for future tests. This can be tricky when you have components that are changing constantly, but can be incredibly handy when your components are stable and shouldn't be getting modified often. Let's write our snapshot test:

  it("renders and matches our snapshot", () => {
const component = renderer.create(<Todo description="Yo" />);
const tree = component.toJSON();
expect(tree).toMatchSnapshot();
});

Remember the renderer we had to import from react-test-renderer? This is where we use it! We create a Todo component via JSX and pass that into the renderer.create() function. We then grab the component structure, transform it into JSON, and verify that it matches the appropriate snapshot from a previous run. This is another early warning system to help catch when someone changes the component but doesn't do anything to update the tests! Let's take a look at the results in our Test Suite:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.162.87