App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Get Started free
Home Guide Snapshot Testing with Jest

Snapshot Testing with Jest

Snapshot testing is a software testing technique that involves capturing and comparing snapshots of the expected output of a system or component. It is commonly used in JavaScript and front-end development but can be applied to other programming languages and domains as well.

The purpose of snapshot testing is to ensure that the output of a piece of code remains consistent over time. It is particularly useful for testing user interfaces, where changes in the visual appearance or structure can impact the user experience.

How Does Snapshot Testing Work

Snapshot testing works by capturing and comparing snapshots of the expected output of a system or component. It is commonly used in JavaScript and front-end development but can be applied to other programming languages and domains as well.

Here’s a step-by-step explanation of how snapshot testing typically works:

Test Setup

Prepare the system or component for testing by configuring any necessary dependencies, data, or states.

  1. Execution: Trigger the specific functionality or action that you want to test. This can involve rendering a UI component, generating a report, or performing any operation that produces an output.
  2. Snapshot Capture: Capture the output of the system or component and save it as a reference snapshot. This can be done using a testing library or framework that provides snapshot testing capabilities.
  3. Snapshot Storage: Store the captured snapshot in a file or database, associating it with the corresponding test case or scenario. This snapshot represents the expected output.
  4. Subsequent Test Runs: On subsequent test runs, the system or component is executed again, and the current output is compared against the stored snapshot.
  5. Snapshot Comparison: The testing framework compares the current output with the stored snapshot and determines if they match. If they match, the test passes. If there are differences, the test fails, indicating a potential regression or unintended change.
  6. Snapshot Update: If the differences are expected and intentional, you can update the snapshot to reflect the new output. This ensures that future test runs consider the updated output as the new expected result.

The comparison between the current output and the stored snapshot typically involves a deep equality check or a structural comparison. The testing library or framework compares the data structures or representations of the output, such as JSON objects, HTML markup, or serialized data, to identify any differences.

When a test fails due to differences between the current output and the stored snapshot, the testing framework usually provides a diff or visual representation highlighting the specific changes. This helps developers identify what has changed and determine whether it is an intended or unintended modification.

Snapshot testing is particularly useful for testing user interfaces where changes in the visual appearance or structure can impact the user experience. By comparing snapshots, developers can quickly detect regressions or unintended modifications that may have occurred due to code changes or updates to dependencies. 

It’s important to note that snapshot testing should not be solely relied upon for testing.

Snapshot Testing in Jest

Snapshot testing is a popular technique in Jest, a JavaScript testing framework, used to verify that the output of a component or function remains consistent over time. When a snapshot test fails, Jest provides a diff between the expected snapshot and the actual output, making it easy to pinpoint the changes that need attention. Snapshot testing simplifies the process of testing complex components or functions, as you don’t need to manually define and maintain the expected output. 

Overall, snapshot testing in Jest offers a convenient way to validate the consistency of your component or function output, making it easier to catch unintended changes and prevent regressions in your codebase.

Prerequisites of Snapshot Testing

Before getting started with snapshot testing in Jest, there are a few prerequisites you need to have in place:

1. Node.js and npm/yarn: Ensure that you have Node.js installed on your development machine. Jest requires Node.js version 10.12.0 or above. npm (Node Package Manager) comes bundled with Node.js, or you can use yarn as an alternative package manager.

2. Jest Installation: Install Jest as a dev dependency in your project. You can use npm or yarn to install Jest. Open your project directory in a terminal and run one of the following commands:

Using npm:


 npm install –save-dev jest

Using yarn:


 yarn add –dev jest

3. Test Environment Setup: If you’re testing React components, make sure you have the necessary dependencies installed for testing React. This typically includes react, react-dom, and @testing-library/react. Install these dependencies as dev dependencies:

Using npm:


 npm install –save-dev react react-dom @testing-library/react

Using yarn:


yarn add –dev react react-dom @testing-library/react

4. Babel Configuration (for JSX): If you’re using JSX syntax in your tests, ensure that you have the necessary Babel configuration set up. This is required to transpile JSX syntax into regular JavaScript code that can be executed by Jest. You can use Babel presets like @babel/preset-react for JSX transformation.

Install Babel dependencies as dev dependencies:

Using npm:


npm install –save-dev @babel/core @babel/preset-react babel-jest

Using yarn:


 yarn add –dev @babel/core @babel/preset-react babel-jest

Create a .babelrc file in the root directory of your project and add the following configuration:


{

“presets”: [“@babel/preset-react”]

}

This configuration tells Babel to use the React preset for transpiling JSX.

Once you have these prerequisites set up, you’re ready to start writing snapshot tests in Jest. You can create test files, import Jest functions, and write test cases to capture and validate snapshots of your component or function outputs.

Setting Up Snapshot Testing: Example

Step 1: Create a New Project –  Start by creating a new directory for your sample project. Open your terminal or command prompt and navigate to the desired location. Then, use the following command to create a new project with a package.json file:


mkdir sample-project

  cd sample-project

  npm init -y

This will create a new directory called sample-project and initialize it as an npm project.

Step 2: Install Jest– Next, you need to install Jest, which is a popular JavaScript testing framework. Run the following command in your terminal:


npm install jest –save-dev

This install Jest as a development dependency and adds it to the package.json file.

Step 3: Create a Test File– Create a new file called sample.test.js in the project directory. This will be our test file where we’ll write our snapshot tests. Open the file in a text editor and add the following code:


test(‘should match snapshot’, () => 

{

const data = {name: ‘John’,age: 30,email: john@example.com};

expect(data).toMatchSnapshot();

});

This test case creates a sample data object and uses the toMatchSnapshot() matcher provided by Jest to generate a snapshot. The toMatchSnapshot() matcher is then used to compare the result with a stored snapshot. If the snapshot exists, Jest compares the result against it. If the snapshot doesn’t exist, Jest creates a new snapshot file.

Step 4: Update package.json– Open the package.json file in your text editor and locate the “scripts” section. Add the following line to the “scripts” section:


“test”: “jest”

This configuration sets up a test script that can be run with npm test command.

Step 5: Run Snapshot Tests- Now, you can run the snapshot tests. In your terminal, run the following command:


npm test

Jest will automatically look for files with the .test.js or .spec.js extension and execute the tests. In our case, it will find sample.test.js and run the snapshot test defined inside.

Step 6: Review Snapshot Output- When you run the snapshot tests for the first time, Jest will generate a snapshot file for your test. The snapshot file will have the same name as your test file but with a .snap extension. 

In this case, Jest will create a file called sample.test.js.snap.

Open the sample.test.js.snap file and you’ll see a serialized representation of the data object. Jest saves this snapshot as the baseline for future tests.

Step 7: Rerun Snapshot Tests– Now, let’s make a deliberate change to our code to see how Jest handles it. Modify the email property of the data object in sample.test.js to a different value.


const data = {name: ‘John’,age: 30,email: ‘changed-email@example.com’};

Save the file and run the tests again with npm test. Jest will compare the modified snapshot with the previously saved snapshot. If the two snapshots match, the test passes. If they differ, Jest will show a diff of the changes and ask for your confirmation to update the snapshot. 

Remember, snapshot testing is useful for capturing the output of code and ensuring it doesn’t change unexpectedly. It’s particularly effective for testing UI components or complex data structures.

Creating Snapshots

To create snapshots in Jest, you can follow these steps:

1. Import Jest functions: At the top of your test file, import the necessary functions from the Jest library:


 import { toMatchSnapshot } from ‘jest-snapshot’;

 import { createSerializer } from ‘jest-snapshot’;

Note: jest-snapshot is built-in with Jest, so you don’t need to install it separately.

2. Configure Snapshot Serializers (Optional): If you’re working with complex data structures or custom objects, you may need to configure Jest’s snapshot serializers to properly serialise and compare the output. This step is usually optional, but it can be useful in certain scenarios.

For example, if you’re using React components, you can configure the react-test-renderer serializer to handle component snapshots. Add the following code to your test file :


expect.addSnapshotSerializer(createSerializer({ mode: ‘deep’ }));

This configures Jest to use the react-test-renderer serializer in deep mode for snapshot serialisation.

3. Write a Test: Write a test case using the test or its function provided by Jest. Within the test case, call the component or function you want to test and capture the output using the toMatchSnapshot() matcher. For example:


test(‘renders MyComponent correctly’, () => { 

Const component = render(<MyComponent />);             expect(component).toMatchSnapshot();

});

In this example, render(<MyComponent />) is called to render the MyComponent component, and the result is captured in the component variable.

4. Run the Test: Run the test command provided by Jest (e.g., jest or npm test). Jest executes the test and compares the output against the stored snapshot. If the output matches the snapshot, the test passes. If there are differences, Jest fails the test and provides a difference between the expected and actual output.

On the first test run, Jest will create a snapshot file (with the same name as your test file and a .snap extension) and pass the test. On subsequent test runs, Jest compares the output with the stored snapshot.

5. Review and Commit Snapshots: After running the test and validating the snapshot, review the generated snapshots in your project directory. The snapshots will be stored in files with the .snap extension. Review the snapshots to ensure they reflect the expected output.

Once you are satisfied with the generated snapshots, commit them to version control. It’s important to include the snapshots in version control so that they can be shared with your team and tracked over time.

By following these steps, you can create and manage snapshots in Jest. The snapshots help you ensure that the output of your components or functions remains consistent and detect any unintended changes or regressions.

Updating Snapshots

To update snapshots in Jest, you can follow these steps:

1. Identify Snapshot Changes: After making intentional changes to your component or function, run your test suite that includes snapshot tests.

2. Detect Snapshot Differences: During the test execution, Jest compares the updated output with the stored snapshots. If there are differences between the new output and the existing snapshots, Jest will fail those specific snapshot tests and provide a diff between the expected and actual output.

3. Decide Whether to Update Snapshots: Review the diff provided by Jest to determine if the changes in the output are expected. If the differences reflect intentional changes, you can proceed to update the snapshots. If the differences are unintended and indicate a regression or unexpected behaviour, you might need to investigate and fix the issue in your code.

4. Update Snapshots: To update the snapshots, re-run the test suite with the —updateSnapshot or –u flag. For example:


jest –updateSnapshot

This flag tells Jest to update the stored snapshots to match the new output. Jest will overwrite the existing snapshot files with the updated snapshots.

Alternatively, you can use the interactive mode with the -i flag to selectively update snapshots:


jest -u -i

This will enter the interactive mode, allowing you to choose which snapshots to update.

5. Verify Updated Snapshots: After updating the snapshots, review the modified snapshot files to ensure they accurately represent the updated output. Manually check the snapshots and verify that the changes align with your expectations.

6. Commit Updated Snapshots: Once you’re satisfied with the updated snapshots, commit the changes to version control. This ensures that the updated snapshots are preserved and shared with your team.

Remember to use caution when updating snapshots and ensure that the changes are intentional. Regularly reviewing and updating snapshots helps maintain accurate representations of the expected output and accommodates deliberate changes in your codebase.

Handling Snapshot Failures

When snapshot tests fail in Jest, it indicates that the output of your component or function has changed since the snapshots were last updated. Handling snapshot failures typically involves reviewing the differences and deciding whether the changes are expected or require further investigation. Here are the steps to handle snapshot failures:

  1. Review the Failure Message: When a snapshot test fails, Jest provides a detailed failure message that includes information about the failing test case and a diff between the expected and actual output. Pay attention to the failure message as it can provide valuable insights into the nature of the changes.
  2. Evaluate the Changes: Examine the difference between the expected and actual output to understand the specific differences. Evaluate whether the changes reflect intentional updates to the component or function or if they indicate a regression or unexpected behaviour. Consider factors such as recent code changes, library updates, or environment differences that could have influenced the output.
  3. Determine Expected Behaviour: Based on your evaluation, determine the expected behaviour of the component or function. If the changes are intentional and align with the expected behaviour, you may need to update the snapshots to reflect the new output. However, if the changes are unintended or unexpected, they might indicate a bug or regression that requires further investigation.
    After updating the snapshots, review the modified snapshot files and verify that they accurately represent the updated output.
  4. Investigate Unexpected Changes: If the changes in the output are unexpected or indicate a regression, further investigation is necessary. Review the relevant code, recent changes, and any dependencies that might have caused the issue. Debug the failing test case and identify the root cause of the unexpected changes. Fix any issues identified and rerun the test to ensure the snapshots are updated accordingly.
  5. Commit Changes: Once you’ve handled the snapshot failures, commit any changes made to the snapshots or code to version control. This ensures that the updated snapshots or bug fixes are properly tracked and shared with your team.
    By carefully reviewing and handling snapshot failures, you can maintain accurate and up-to-date snapshots that reflect the expected output of your components or functions. Regularly monitoring and addressing snapshot failures helps catch unintended changes and ensures the reliability of your tests.

Interactive Snapshot Mode

The interactive snapshot mode in Jest allows you to selectively update or delete individual snapshots during the test execution. This mode provides a convenient way to handle snapshot failures and manage your snapshots. Here’s how to use the interactive snapshot mode:

1. Run Jest in Interactive Mode: Execute your test suite with the –i or —interactive flag:
This command launches Jest in interactive mode.


jest -i

2. Review Snapshot Differences: When Jest encounters a snapshot failure, it presents the diff between the expected and actual output. You’ll see options to update or skip the snapshot for that specific test case.

3. Choose an Action: Jest prompts you to choose an action for each snapshot failure. You can select one of the following options:

  • u or i: Update the snapshot for the current test case.
  • d or o: Remove the snapshot for the current test case.
  • s or n: Skip the snapshot update or deletion for the current test case.
  • q: Quit the interactive mode and stop running the tests.

You can type the corresponding letter or use the arrow keys to navigate and select an option.

4. Perform the Chosen Action: After selecting an action, Jest applies the chosen action to the current snapshot and continues with the test execution. If you choose to update the snapshot, Jest will update it to reflect the new output. If you choose to delete the snapshot, Jest will remove it from the snapshot files. If you choose to skip the action, Jest will keep the existing snapshot without making any changes.

5. Repeat for Other Snapshot Failures: Jest will continue running the test suite and present the interactive prompt for each subsequent snapshot failure. Review the differences, choose the appropriate action, and Jest will apply it accordingly.

6. Complete the Test Execution: After handling all the snapshot failures or quitting the interactive mode, Jest completes the test execution and provides a summary of the results.

7. Commit Snapshot Changes: Once you’ve finished handling the snapshot failures, commit the updated or deleted snapshots to version control. This ensures that the changes are tracked and shared with your team.

The interactive snapshot mode allows you to selectively update or delete snapshots during the test execution, providing greater control over managing your snapshots. It helps streamline the snapshot review process and makes it easier to handle snapshot failures efficiently.

Best Practices for Snapshot Testing

Here are some best practices for snapshot testing in Jest:

  1. Use Descriptive Test Names: Give your test cases meaningful and descriptive names that clearly indicate what is being tested. This helps in identifying the purpose of the test and makes it easier to understand failures.
  2. Isolate Dependencies: Ensure that your snapshots are not affected by external factors or dependencies. Mock or stub any external dependencies to have full control over the test environment and maintain the stability of your snapshots.
  3. Avoid Unnecessary Snapshots: Limit the use of snapshots to cases where they provide significant value. Not all components or functions require snapshot testing, especially when the output is simple or static. Use snapshots judiciously to focus on critical or complex parts of your codebase.
  4. Regularly Review and Update Snapshots: As your code evolves, review and update your snapshots to reflect intentional changes. Relying on outdated snapshots can lead to false positives or missed regressions. Schedule regular reviews of your snapshots and update them as needed.
  5. Avoid Snapshot Pollution: Ensure that your snapshots are concise and only capture the necessary information. Avoid including dynamic data, timestamps, or irrelevant details that can lead to unnecessary changes in the snapshots. This helps maintain stability and reduces noise in snapshot diffs.
  6. Review Diffs Carefully: When a snapshot test fails, carefully review the difference between the expected and actual output. Understand the nature of the changes and evaluate whether they align with the expected behaviour. This helps in distinguishing intentional changes from unexpected regressions.
  7. Use Inline Snapshots for Dynamic Output: Inline snapshots allow you to capture and update snapshots directly in your test cases. They are particularly useful for testing components or functions with dynamic output. Inline snapshots make it easier to capture the expected output in the test itself, reducing the need for separate snapshot files.
  8. Utilise Snapshot Serialisation: Configure Jest’s snapshot serialisation to handle complex data structures or custom objects. Use appropriate serializers for libraries like React, Redux, or GraphQL to ensure accurate snapshot comparisons. Custom serializers can be created for specific scenarios where default serialisation is not sufficient.
  9. Version Control Snapshots: Include your snapshot files in version control to track changes over time. This allows your team to collaborate and review changes to snapshots. Version control also helps identify when and why snapshots were updated, aiding in debugging and ensuring the stability of your tests.
  10. Combine with Traditional Testing Techniques: Snapshot testing should complement, not replace, other testing techniques such as unit tests, integration tests, and manual testing. Use snapshot testing in conjunction with other testing methodologies to achieve comprehensive test coverage.

By following these best practices, you can ensure effective and reliable snapshot testing in your Jest test suite. Snapshots can be a valuable tool for capturing and validating the output of your components or functions, aiding in code maintenance and preventing regressions.

Tools for Snapshot Testing

When it comes to snapshot testing in JavaScript, Jest is the most widely used testing framework that provides built-in support for snapshot testing. Jest offers powerful snapshot functionality and is commonly used for snapshot testing in various JavaScript projects. However, there are also other tools available that can complement or enhance snapshot testing capabilities. Here are a few notable tools:

  • React Testing Library: React Testing Library is a popular testing utility for React applications. It provides a toMatchSnapshot() function that works alongside Jest’s snapshot testing. Additionally, React Testing Library emphasises testing user interactions and component behaviour rather than implementation details, making it a great choice for snapshot testing React components.
  • Enzyme: Enzyme is another testing utility for React applications. It provides a toJSON() method that can be used in combination with Jest’s snapshot testing. Enzyme offers a different approach to testing React components, focusing on component traversal and manipulation. It can be used as an alternative or alongside React Testing Library.
  • React-test-renderer: The react-test-renderer package is part of React’s official testing utilities. It allows you to render React components to a JSON-like structure, which can then be compared using Jest’s snapshot testing. It provides a low-level API for testing components without the need for a full DOM.
  • Testing Library for other frameworks: Apart from React Testing Library, there are testing libraries available for other JavaScript frameworks like Vue.js (Vue Testing Library), Angular (Angular Testing Library), and Svelte (Svelte Testing Library). These libraries often provide snapshot testing capabilities that align with the principles of their respective frameworks.
  • Snapshot Diff: Snapshot Diff is a tool that enhances the diffing experience when dealing with snapshot failures. It provides a clearer and more readable diff between the expected and actual output, making it easier to understand the changes and identify potential issues.
  • Storybook: Storybook is a popular tool for building UI component libraries. It also includes snapshot testing capabilities through add-ons like Storyshot. Story Shot allows you to take snapshots of your Storybook stories, ensuring that components render consistently across different states and variations.

These tools can assist in snapshot testing, provide additional utilities for testing frameworks, and enhance the overall testing experience. Consider exploring these options based on your specific project requirements and the JavaScript framework you are using.

Advantages and Disadvantages of Snapshot Testing

Advantages of Snapshot Testing

Snapshot testing offers several benefits that can improve the efficiency and reliability of your testing process. Here are some key benefits of snapshot testing:

  1. Simplified Test Maintenance: Snapshots serve as a reference for the expected output of your components or functions. By capturing the output and storing it as a snapshot, you can easily compare future test runs against the stored reference. This simplifies test maintenance by automatically detecting any unintentional changes in the output and highlighting them as test failures. It helps catch regressions early and reduces the need for manually updating test assertions.
  2. Readable and Concise Tests: Snapshot tests provide a clear and concise representation of the expected output. The snapshots themselves act as self-documenting test cases, making it easier for developers to understand the intended behaviour. The concise nature of snapshots helps reduce the boilerplate code required for setting up and asserting the output, resulting in more readable and maintainable tests.
  3. Fast Feedback Loop: Snapshot testing can significantly speed up the feedback loop during development. Once the initial snapshots are created, subsequent test runs only compare the current output with the stored snapshots. This eliminates the need to recompute the expected output or perform complex assertions for each test run. As a result, snapshot tests can provide fast and efficient feedback on whether the output has changed or remains consistent.
  4. Detecting Visual Changes: Snapshot testing is particularly valuable for UI components and visual regression testing. By capturing the rendered output of components as snapshots, you can easily detect any unintended visual changes. Snapshots act as a visual baseline, allowing you to quickly identify pixel-level differences, layout shifts, or styling issues. This helps maintain consistent and visually appealing user interfaces.
  5. Collaboration and Documentation: Snapshots can serve as a form of documentation, providing a historical record of the expected output for components or functions. They can help onboard new team members, facilitate code reviews, and promote collaboration within the team. By reviewing and updating snapshots regularly, the team can ensure that the snapshots accurately reflect the intended behaviour and serve as reliable references.
  6. Consistency across Environments: Snapshot tests can help ensure consistent behaviour across different environments. Since the snapshots are platform-independent representations of the output, they can be executed on different machines or CI/CD environments. This helps catch any environment-specific issues or inconsistencies in the output, ensuring that the components or functions behave consistently across different setups.

By leveraging snapshot testing, you can streamline your testing process, improve code quality, and detect regressions early in the development cycle. Snapshots provide a practical and efficient way to validate the output of your components or functions and contribute to a robust testing strategy.

Disadvantages of Snapshot Testing

While snapshot testing offers numerous benefits, it’s important to be aware of its limitations and potential challenges. Here are some limitations of snapshot testing:

  1. Limited Contextual Information: Snapshots capture the output of components or functions at a specific point in time. Snapshots don’t provide information about the input data, user interactions, or the specific conditions under which the output was generated. This can make it harder to diagnose and debug issues solely based on snapshot comparisons.
  2. False Positives and False Negatives: Snapshot tests can sometimes lead to false positives and false negatives. A false positive occurs when a test fails due to an intentional change in the output that hasn’t been updated in the snapshot. Handling false positives and false negatives requires careful review and maintenance of the snapshot tests.
  3. Brittle Tests: If a component generates dynamic content like timestamps or random values, the snapshots may need frequent updates, leading to test maintenance overhead. Over-reliance on snapshots for testing complex or rapidly changing components can lead to excessive test failures and hinder development productivity
  4. Lack of Semantic Understanding: Snapshots only capture the structure and values of the output without understanding their semantic meaning. As a result, snapshot tests can miss subtle logic errors or incorrect behaviour that may not be apparent from the output alone. It’s crucial to complement snapshot testing with other testing techniques, such as unit tests or integration tests, to cover semantic correctness and edge cases.
  5. Snapshot Size and Performance: Large snapshots can impact test performance and increase test execution time. Storing and comparing large snapshots can be resource-intensive, especially in cases where the output contains a significant amount of data or complex structures. Additionally, large snapshots can make it challenging to identify specific differences and review the diff in case of failures.
  6. Maintaining Legacy Snapshots: As your codebase evolves, legacy snapshots may become outdated and lose their relevance. It’s important to regularly review and update snapshots to avoid relying on outdated references that might not reflect the current behaviour accurately. Maintaining a balance between updating existing snapshots and managing backward compatibility can be a challenge, especially in large codebases.

To mitigate these limitations, it’s essential to use snapshot testing judiciously alongside other testing techniques. Regularly review and update snapshots, consider the context of the tests, and ensure that the snapshots accurately represent the intended behaviour. A combination of snapshot testing, unit tests, integration tests, and manual testing provides a more comprehensive approach to ensuring the quality and correctness of your codebase.

Conclusion

Snapshot testing is a valuable technique in software testing, commonly used in JavaScript projects with tools like Jest. It involves capturing and comparing the expected output of components or functions. Snapshots serve as concise and readable tests, simplifying test maintenance by eliminating the need for manual assertion updates. They provide a fast feedback loop, detecting unintended changes and visual regressions in UI components. 

Snapshot testing aids collaboration and documentation, serving as a historical record of expected behaviour. However, it has limitations, such as limited contextual information and the potential for false positives/negatives. It is best used in conjunction with other testing techniques to ensure semantic correctness and cover edge cases. Regularly reviewing and updating snapshots is important for accuracy. Overall, snapshot testing enhances testing efficiency and contributes to higher-quality software development.

Frequently Asked Questions

What is the Difference between Snapshot Testing and Unit Testing?

Snapshot testing and unit testing are both important techniques in software testing, but they serve different purposes and focus on different aspects of testing.

Unit Testing:

Unit testing is a practice of testing individual units or components of a software system in isolation. It aims to verify the correctness of a specific unit of code, such as a function, method, or class. Unit tests typically involve writing test cases that exercise the unit under test and assert the expected behaviour of that unit.

Key characteristics of unit testing include:

  • Testing small, isolated units of code.
  • Mocking or stubbing dependencies to isolate the unit being tested.
  • Focusing on specific input-output scenarios and edge cases.
  • Emphasizing the correctness of individual units and their behaviour.
  • Providing fast feedback during development, as unit tests are typically executed frequently.

Snapshot Testing:

Snapshot testing, on the other hand, is a technique for capturing and validating the output of components or functions. It involves storing a snapshot of the output and comparing it against subsequent test runs to detect any changes. Snapshot tests focus on the behaviour and structure of the output rather than the internal implementation details of the unit being tested.

Key characteristics of snapshot testing include:

  • Capturing and storing the expected output of components or functions.
  • Comparing subsequent test runs against the stored snapshots.
  • Simplifying test maintenance by avoiding manual assertion updates.
  • Detecting unintended changes or regressions in the output.
  • Providing concise and readable tests that act as self-documentation.

While, unit testing verifies the correctness of individual units of code, focusing on specific input-output scenarios and ensuring the behaviour of each unit is as expected. Snapshot testing, on the other hand, captures and validates the output of components or functions, simplifying test maintenance and detecting unintended changes. Unit testing targets the internal implementation of code units, while snapshot testing focuses on the output and structure of components or functions. Both techniques are valuable and often used in combination to achieve maximum test coverage.

What is the difference between snapshot testing and visual regression testing?

Snapshot testing and visual regression testing are two different approaches used in software testing, particularly in the context of UI testing. While they both involve capturing and comparing visual representations of components, they serve different purposes and have distinct characteristics.

  • Snapshot Testing:

Snapshot testing, as discussed earlier, is a technique for capturing and validating the output of components or functions. It captures the rendered output of a component or UI element and stores it as a snapshot. Subsequent test runs compare the current output against the stored snapshot to detect any changes. Snapshot testing is primarily focused on validating the structure and content of the output, ensuring that it remains consistent over time. It is useful for detecting unintentional changes and regressions in the UI, such as layout shifts, content updates, or styling modifications.

  • Visual Regression Testing:

Visual regression testing, on the other hand, specifically aims to identify visual differences between different versions of a UI or webpage. It involves capturing screenshots or visual representations of a UI component or webpage and comparing them against reference images or previous versions. Visual regression testing is concerned with detecting any unintended visual changes, such as differences in layout, styling, or graphical elements. It helps maintain visual consistency and prevents regressions in the UI appearance.

Key differences between snapshot testing and visual regression testing include:

  • Scope: Snapshot testing focuses on capturing and validating the output of individual components or functions, while visual regression testing operates on a broader level, comparing the visual appearance of entire UI components or webpages.
  • Purpose: Snapshot testing primarily checks for structural and content changes in the output, ensuring consistency. Visual regression testing specifically targets visual differences, including layout, styling, and graphical changes.
  • Technique: Snapshot testing captures and compares snapshots of the output, while visual regression testing involves capturing and comparing visual representations such as screenshots or images.
  • Level of Granularity: Snapshot testing can capture fine-grained differences in the output of individual components, allowing for detailed comparisons. Visual regression testing focuses on overall visual differences, often at a higher level, comparing entire components or webpages.
  • Tooling: Snapshot testing is typically integrated into testing frameworks like Jest, providing built-in functionality for snapshot comparison. Visual regression testing often requires specialized tools or libraries, such as Puppeteer, Selenium, Percy, or App Percy which offer features specifically designed for visual comparison.

While, snapshot testing verifies the structure and content of UI components, while visual regression testing focuses on detecting visual differences between different versions of the UI.

Tags
UI Testing Visual Testing

Featured Articles

How to write Snapshot Tests for React Components with Jest?

How to perform Storybook Visual Testing?

App & Browser Testing Made Easy

Seamlessly test across 20,000+ real devices with BrowserStack