0
0
React Nativemobile~20 mins

Snapshot testing in React Native - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Simple Button Screen
A screen with a button that changes text when pressed. We will create a snapshot test to verify the UI does not change unexpectedly.
Target UI
┌───────────────────────────┐
│       Simple Button       │
│                           │
│       [ Press me ]         │
│                           │
│ Text: Not pressed yet     │
└───────────────────────────┘
Display a button labeled 'Press me'.
Show a text below the button that says 'Not pressed yet' initially.
When the button is pressed, change the text to 'Button pressed!'.
Write a snapshot test to capture the initial UI and verify it matches the expected snapshot.
Starter Code
React Native
import React, { useState } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';

export default function SimpleButtonScreen() {
  const [pressed, setPressed] = useState(false);

  return (
    <View style={styles.container}>
      {/* TODO: Add Button here */}
      {/* TODO: Add Text here to show pressed state */}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 16
  }
});
Task 1
Task 2
Solution
React Native
import React, { useState } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';

export default function SimpleButtonScreen() {
  const [pressed, setPressed] = useState(false);

  return (
    <View style={styles.container}>
      <Button title="Press me" onPress={() => setPressed(true)} />
      <Text style={styles.text} accessibilityRole="text">
        {pressed ? 'Button pressed!' : 'Not pressed yet'}
      </Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 16
  },
  text: {
    marginTop: 20,
    fontSize: 18
  }
});

This screen uses React Native's useState hook to track if the button was pressed.

The Button component triggers setPressed(true) on press, changing the text below it.

The Text component updates to show the current state.

For snapshot testing, you capture the initial render (before pressing) to ensure the UI stays consistent over time.

Final Result
Completed Screen
┌───────────────────────────┐
│       Simple Button       │
│                           │
│       [ Press me ]         │
│                           │
│ Text: Not pressed yet     │
└───────────────────────────┘
When user taps 'Press me', the text changes to 'Button pressed!'.
Snapshot test captures the initial UI with 'Not pressed yet' text.
Stretch Goal
Write a snapshot test using Jest and React Test Renderer to verify the initial UI of SimpleButtonScreen.
💡 Hint
Use 'react-test-renderer' to create a snapshot of the component and expect it to match the saved snapshot file.