0
0
React Nativemobile~20 mins

Detox for E2E testing in React Native - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Simple Counter
A screen with a counter that increments when a button is tapped. This app will be used to demonstrate Detox end-to-end testing.
Target UI
-------------------
| Simple Counter   |
|-----------------|
| Count: 0        |
|                 |
| [ Increment ]   |
-------------------
Display a count starting at 0
Show a button labeled 'Increment'
When the button is tapped, increase the count by 1
The count text updates immediately
Starter Code
React Native
import React, { useState } from 'react';
import { SafeAreaView, Text, Button, StyleSheet } from 'react-native';

export default function SimpleCounter() {
  const [count, setCount] = useState(0);

  // TODO: Implement increment function and UI

  return (
    <SafeAreaView style={styles.container}>
      {/* TODO: Display count and increment button here */}
    </SafeAreaView>
  );
}

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

export default function SimpleCounter() {
  const [count, setCount] = useState(0);

  const increment = () => setCount(count + 1);

  return (
    <SafeAreaView style={styles.container}>
      <Text accessibilityLabel="countText" style={styles.countText}>Count: {count}</Text>
      <Button
        title="Increment"
        onPress={increment}
        accessibilityLabel="incrementButton"
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  countText: {
    fontSize: 24,
    marginBottom: 20,
  },
});

This simple React Native app uses a useState hook to keep track of the count. The increment function updates the count state by adding 1 each time the button is pressed. The Text component shows the current count, and the Button triggers the increment. Accessibility labels are added to help Detox identify UI elements during testing.

Final Result
Completed Screen
-------------------
| Simple Counter   |
|-----------------|
| Count: 0        |
|                 |
| [ Increment ]   |
-------------------
When the user taps the 'Increment' button, the count number increases by 1 immediately.
The count text updates to show the new number.
Stretch Goal
Write a Detox test that launches the app, taps the 'Increment' button, and verifies the count text updates to 'Count: 1'.
💡 Hint
Use Detox's 'element(by.label())' to find the button and text, then use 'tap()' and 'expect().toHaveText()' to test.