techStackGuru

Jest Update Snapshot


When you want to ensure that your user interface does not alter unexpectedly, snapshot tests are a very helpful tool.

In a typical snapshot test scenario, a UI component is rendered, a snapshot is taken, and the snapshot is compared to a reference snapshot file kept with the test.

If the two snapshots differ, either the change is unexpected or the reference snapshot needs to be updated to reflect the new version of the UI component for the test to pass.

jest-test

First, install react-test-renderer


npm install react-test-renderer

import renderer from 'react-test-renderer';

describe("Jest Snapshot Testing", () => {
    it("Matches DOM Snapshot", () => {
      const domTree = renderer.create(<App />).toJSON();
      expect(domTree).toMatchSnapshot();
    });
  });

npm test
jest-test

App.js file


function App() {

    return (
      <div className="App">
        
        <input type="checkbox"/>
        
        <h1>Techstackguru</h1>
  
        <Button>Search</Button>
  
        <img width="100" height="50" />
      </div>
    );
  }
  
export default App;

App.test.js.snap file

jest-test

previous-button
next-button