Bird
Raised Fist0
React Nativemobile~15 mins

Snapshot testing in React Native - Deep Dive

Choose your learning style10 modes available
Overview - Snapshot testing
What is it?
Snapshot testing is a way to check if the user interface of a mobile app looks the same as before. It saves a picture-like record of a UI component and compares it every time you run tests. If the UI changes unexpectedly, the test alerts you. This helps catch bugs early without manually checking the app.
Why it matters
Without snapshot testing, developers must manually check every UI change, which is slow and error-prone. Bugs can slip into the app unnoticed, causing bad user experiences. Snapshot testing automates this check, saving time and making sure the app looks right after every change.
Where it fits
Before learning snapshot testing, you should know basic React Native components and how to write simple tests. After mastering snapshot testing, you can learn more advanced testing methods like integration and end-to-end testing to cover app behavior beyond UI.
Mental Model
Core Idea
Snapshot testing captures a saved image of a UI component’s structure to quickly detect unexpected changes in its appearance.
Think of it like...
Snapshot testing is like taking a photo of your room to remember how it looks. Later, you compare new photos to see if anything moved or changed without your knowledge.
┌─────────────────────────────┐
│ Render UI Component          │
├─────────────────────────────┤
│ Generate Snapshot (JSON)     │
├─────────────────────────────┤
│ Save Snapshot File           │
├─────────────────────────────┤
│ On Test Run: Render Component│
│ Compare with Saved Snapshot  │
├───────────────┬─────────────┤
│ Match         │ Mismatch    │
│ Pass Test     │ Fail Test   │
└───────────────┴─────────────┘
Build-Up - 7 Steps
1
FoundationWhat is Snapshot Testing
🤔
Concept: Introduce the basic idea of snapshot testing as saving UI output for future comparison.
Snapshot testing saves the rendered output of a React Native component as a snapshot file. When you run tests again, it compares the current output to the saved snapshot. If they differ, the test fails, showing what changed.
Result
You get a saved snapshot file representing the UI component’s structure at a point in time.
Understanding that snapshot testing stores a UI 'picture' as code helps you see how it catches unexpected changes automatically.
2
FoundationSetting Up Snapshot Tests
🤔
Concept: Learn how to write a simple snapshot test using React Native testing tools.
Use Jest, the default testing tool for React Native. Write a test that renders a component with @testing-library/react-native and calls expect(tree).toMatchSnapshot(). This creates or compares the snapshot file.
Result
A test file that runs and creates a snapshot file if none exists, or compares to existing snapshots.
Knowing how to set up snapshot tests lets you automate UI checks with minimal code.
3
IntermediateUnderstanding Snapshot Files
🤔Before reading on: do you think snapshot files store images or code? Commit to your answer.
Concept: Snapshot files store a serialized version of the UI tree, not actual images.
Snapshots are saved as plain text files containing JSON-like structures representing the UI elements and their props. This makes them easy to review and version control.
Result
You see snapshot files in your project folder that look like code, showing component structure and props.
Knowing snapshots are code-like structures explains why they are easy to diff and review in version control.
4
IntermediateUpdating Snapshots Safely
🤔Before reading on: should you update snapshots automatically whenever tests fail? Commit to yes or no.
Concept: Learn when and how to update snapshots to reflect intentional UI changes.
If a UI change is expected, run tests with the --updateSnapshot flag to refresh snapshots. Always review changes before updating to avoid hiding bugs.
Result
Snapshots update only when you confirm UI changes are correct, keeping tests reliable.
Understanding controlled snapshot updates prevents accidental acceptance of bugs as correct UI.
5
IntermediateLimitations of Snapshot Testing
🤔
Concept: Recognize what snapshot testing can and cannot do.
Snapshot tests check UI structure but not behavior or user interactions. They can produce false positives if snapshots are updated without review. Also, large snapshots can be hard to maintain.
Result
You know snapshot testing is one tool among many, best for catching unexpected UI changes but not all bugs.
Knowing snapshot testing limits helps you combine it with other testing methods for full coverage.
6
AdvancedBest Practices for Snapshot Tests
🤔Before reading on: do you think snapshot tests should cover entire screens or small components? Commit to your answer.
Concept: Learn how to write maintainable snapshot tests by focusing on small, stable components.
Test small, reusable components rather than whole screens to keep snapshots simple. Use descriptive test names and review snapshots regularly. Avoid snapshot tests for frequently changing UI parts.
Result
Your snapshot tests stay clear, fast, and useful over time.
Understanding test scope and maintenance keeps snapshot testing effective and prevents test bloat.
7
ExpertInternals of Snapshot Comparison
🤔Before reading on: do you think snapshot comparison is a pixel-by-pixel image check or text diff? Commit to your answer.
Concept: Explore how Jest compares snapshots using text diffs of serialized UI trees.
Jest compares the current rendered output's serialized JSON structure to the saved snapshot file using a line-by-line text diff. It highlights added, removed, or changed lines to show UI differences clearly.
Result
You see detailed diffs in test output showing exactly what changed in the UI structure.
Knowing snapshot comparison is a text diff explains why snapshots are fast and easy to review, unlike image-based tests.
Under the Hood
When a snapshot test runs, the React Native component is rendered to a virtual tree structure in memory. This tree is serialized into a JSON-like string that captures the component type, props, and children. Jest saves this string as a snapshot file. On future runs, Jest renders the component again, serializes it, and compares the new string to the saved snapshot using a text diff algorithm. If differences exist, Jest reports a test failure with a detailed diff.
Why designed this way?
Snapshot testing was designed to automate UI regression checks without needing complex image comparisons. Text-based snapshots are easy to store, diff, and review in code repositories. This approach balances speed, readability, and maintainability. Alternatives like pixel-based image snapshots are slower and harder to manage, so text snapshots became the standard.
┌───────────────┐
│ Render UI     │
│ Component    │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Serialize to  │
│ JSON-like     │
│ Snapshot      │
└──────┬────────┘
       │
       ▼
┌───────────────┐       ┌───────────────┐
│ Save Snapshot │◄─────▶│ Load Snapshot │
│ File         │       │ File          │
└──────┬────────┘       └──────┬────────┘
       │                       │
       ▼                       ▼
┌───────────────┐       ┌───────────────┐
│ New Render    │       │ Compare Text  │
│ Serialize    │       │ Diff          │
└──────┬────────┘       └──────┬────────┘
       │                       │
       └───────────────┬───────┘
                       ▼
                ┌───────────────┐
                │ Test Pass or  │
                │ Fail with Diff│
                └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does snapshot testing check if the app behaves correctly when users tap buttons? Commit yes or no.
Common Belief:Snapshot testing verifies all app behavior including user interactions.
Tap to reveal reality
Reality:Snapshot testing only checks the UI structure output, not dynamic behavior or user actions.
Why it matters:Relying only on snapshot tests can miss bugs in app logic or interaction flows, causing broken features.
Quick: Should you update snapshots automatically whenever tests fail? Commit yes or no.
Common Belief:If a snapshot test fails, just update the snapshot to fix it immediately.
Tap to reveal reality
Reality:You should only update snapshots when UI changes are intentional and verified, not blindly.
Why it matters:Blindly updating snapshots hides real bugs and defeats the purpose of testing.
Quick: Are snapshot files images stored in your project? Commit yes or no.
Common Belief:Snapshot files are pictures or screenshots of the UI.
Tap to reveal reality
Reality:Snapshot files are text files storing serialized UI component trees, not images.
Why it matters:Misunderstanding this leads to confusion about how snapshots work and how to review them.
Quick: Can snapshot testing catch layout or style bugs perfectly? Commit yes or no.
Common Belief:Snapshot testing always catches visual layout and style bugs.
Tap to reveal reality
Reality:Snapshot testing may miss subtle visual bugs because it compares structure, not rendered pixels.
Why it matters:Relying solely on snapshots can miss UI bugs that only appear visually, requiring complementary tests.
Expert Zone
1
Snapshot tests can be brittle if components include non-deterministic data like timestamps or random IDs; mocking these is essential.
2
Using inline snapshots inside test files improves readability and keeps snapshots close to test logic, aiding maintenance.
3
Large snapshots with deeply nested components can slow tests and make diffs hard to read; splitting tests into smaller components helps.
When NOT to use
Avoid snapshot testing for highly dynamic UI parts that change often or depend on external data. Use interaction or visual regression tests instead for those cases.
Production Patterns
In production, snapshot tests are integrated into CI pipelines to catch UI regressions early. Teams combine snapshots with unit and integration tests for full coverage. Snapshots are reviewed carefully during code reviews to ensure UI changes are intentional.
Connections
Visual Regression Testing
Related testing method focusing on pixel-level UI changes.
Understanding snapshot testing’s text-based approach clarifies why visual regression testing is used for catching subtle style or layout bugs snapshots might miss.
Version Control Systems
Snapshot files are stored and diffed in version control like code.
Knowing how snapshots appear in git diffs helps developers review UI changes alongside code changes effectively.
Memory Palaces (Mnemonic Technique)
Both involve storing structured snapshots for later comparison or recall.
Recognizing that snapshot testing stores a mental 'picture' of UI structure is similar to how memory palaces store mental images for recall.
Common Pitfalls
#1Updating snapshots without reviewing changes.
Wrong approach:jest --updateSnapshot (run blindly whenever tests fail)
Correct approach:Review test failure diffs carefully, then run jest --updateSnapshot only if UI changes are intentional.
Root cause:Misunderstanding that snapshot updates should be deliberate, not automatic.
#2Writing snapshot tests for large, complex screens.
Wrong approach:expect(render().toJSON()).toMatchSnapshot()
Correct approach:Write snapshot tests for small, reusable components instead of entire screens.
Root cause:Not realizing large snapshots are hard to maintain and review.
#3Including dynamic data in snapshots without mocking.
Wrong approach:Render components with current timestamps or random IDs in snapshots.
Correct approach:Mock dynamic values to fixed constants before snapshot testing.
Root cause:Not accounting for non-deterministic data causing false test failures.
Key Takeaways
Snapshot testing saves a serialized version of UI components to detect unexpected changes automatically.
Snapshots are text files representing UI structure, not images, making them easy to review and version control.
Always review snapshot diffs carefully before updating to avoid hiding bugs.
Snapshot testing is best for small, stable components and should be combined with other tests for full app coverage.
Understanding snapshot internals and limitations helps write maintainable and effective UI tests.

Practice

(1/5)
1. What is the main purpose of snapshot testing in React Native?
easy
A. To check the app's performance speed
B. To test network requests and API responses
C. To detect unexpected changes in the UI output
D. To validate user input formats

Solution

  1. Step 1: Understand snapshot testing goal

    Snapshot testing saves the UI output to detect changes later.
  2. Step 2: Identify what snapshot testing checks

    It compares future UI renders to saved snapshots to catch unexpected changes.
  3. Final Answer:

    To detect unexpected changes in the UI output -> Option C
  4. Quick Check:

    Snapshot testing = UI change detection [OK]
Hint: Snapshot testing checks UI changes, not logic or speed [OK]
Common Mistakes:
  • Confusing snapshot testing with API or performance tests
  • Thinking it tests user input validation
  • Assuming it measures app speed
2. Which of the following is the correct way to write a basic snapshot test in React Native using Jest?
easy
A. render().toMatchSnapshot();
B. expect(render()).toMatchSnapshot();
C. expect().toMatchSnapshot();
D. expect(render()).toBeSnapshot();

Solution

  1. Step 1: Recall Jest snapshot syntax

    Jest requires wrapping the rendered output in expect() and calling toMatchSnapshot().
  2. Step 2: Check each option's syntax

    expect(render()).toMatchSnapshot(); correctly wraps render output in expect() and calls toMatchSnapshot(). Others miss expect() or use wrong matcher.
  3. Final Answer:

    expect(render()).toMatchSnapshot(); -> Option B
  4. Quick Check:

    Use expect(render()).toMatchSnapshot() [OK]
Hint: Always wrap render output in expect() before toMatchSnapshot() [OK]
Common Mistakes:
  • Omitting expect() around render output
  • Using incorrect matcher like toBeSnapshot()
  • Passing component directly to expect() without render
3. Given this snapshot test code:
const tree = render().toJSON();
expect(tree).toMatchSnapshot();

What will happen if the Button's title changes to "Press" in the next test run?
medium
A. The test will fail because the snapshot does not match
B. The test will pass because title changes are ignored
C. The test will throw a syntax error
D. The test will pass but log a warning

Solution

  1. Step 1: Understand snapshot comparison

    Snapshots save the UI output including props like title. Changing title changes output.
  2. Step 2: Effect of changing title on test

    Since the new render differs from saved snapshot, Jest will fail the test to alert the change.
  3. Final Answer:

    The test will fail because the snapshot does not match -> Option A
  4. Quick Check:

    Changed UI props cause snapshot test failure [OK]
Hint: Any UI change breaks snapshot test unless updated [OK]
Common Mistakes:
  • Thinking snapshot ignores prop changes
  • Expecting test to pass with changed UI
  • Confusing snapshot failure with syntax errors
4. You wrote this snapshot test:
test('renders correctly', () => {
  const tree = render();
  expect(tree).toMatchSnapshot();
});

But Jest throws an error: expect(received).toMatchSnapshot is not a function. What is the likely cause?
medium
A. You should use toBeSnapshot() instead
B. You need to import toMatchSnapshot manually
C. The component MyComponent is missing props
D. You forgot to call .toJSON() on the render output

Solution

  1. Step 1: Understand render output type

    render() returns an object, not a JSON serializable tree. toMatchSnapshot() works on JSON.
  2. Step 2: Fix by calling toJSON()

    Calling toJSON() converts render output to snapshot-friendly format, enabling toMatchSnapshot() usage.
  3. Final Answer:

    You forgot to call .toJSON() on the render output -> Option D
  4. Quick Check:

    Call render().toJSON() before expect() [OK]
Hint: Always call .toJSON() on render output before snapshot [OK]
Common Mistakes:
  • Skipping .toJSON() call on render output
  • Trying to import toMatchSnapshot manually
  • Using wrong matcher like toBeSnapshot()
5. You want to update your snapshot after intentionally changing your component's UI. Which command should you run to update the snapshot files?
hard
A. jest -u
B. jest --updateSnapshots
C. jest --updateSnapshot
D. jest --update-snapshots

Solution

  1. Step 1: Recall Jest snapshot update command

    The correct Jest flag to update snapshots is -u or --updateSnapshot.
  2. Step 2: Identify exact command

    Among options, only jest -u is the correct short form. Others are invalid or misspelled.
  3. Final Answer:

    jest -u -> Option A
  4. Quick Check:

    Use jest -u to update snapshots [OK]
Hint: Use jest -u to update snapshots after UI changes [OK]
Common Mistakes:
  • Typing incorrect or misspelled flags
  • Trying to update snapshots without flags
  • Confusing updateSnapshot with updateSnapshots
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard