Testing Lab 2: Snapshot Tests
Objectives
- Install React's Test Renderer
- Create Your First Snapshot Test
Steps
Install React's Test Renderer
Open a
command prompt
(Windows) orterminal
(Mac).Change the current directory to
code\keeptrack
.Run one of the following sets of commands:
npm
npm i react-test-renderer --save-dev
npm i @types/react-test-renderer --save-devYarn
yarn add react-test-renderer
yarn add @types/react-test-renderer --save-dev
Create Your First Snapshot Test
Add a snapshot test for the component. Organize the tests in a suite (describe function).
src\home\HomePage.test.tsx
import React from 'react';
import HomePage from './HomePage';
+ import renderer from 'react-test-renderer';
+ describe('<HomePage />', () => {
test('should render without crashing', () => {
render(<HomePage />);
});
+ test('snapshot', () => {
+ const tree = renderer.create(<HomePage />).toJSON();
+ expect(tree).toMatchSnapshot();
+ });
+ });Verify the snapshot is created.
› 1 snapshot written.
Open
src\home\__snapshots__\HomePage.test.tsx.snap
and review the contents.