Bird
Raised Fist0
React Nativemobile~20 mins

React Native Testing Library - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
React Native Testing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate
2:00remaining
What is the output of this test?
Given this React Native component and test, what will the test output be?
React Native
import React from 'react';
import { Text, Button, View } from 'react-native';
import { render, fireEvent } from '@testing-library/react-native';

function Counter() {
  const [count, setCount] = React.useState(0);
  return (
    <View>
      <Text testID="count-text">Count: {count}</Text>
      <Button title="Increment" onPress={() => setCount(count + 1)} />
    </View>
  );
}

const { getByTestId, getByText } = render(<Counter />);
fireEvent.press(getByText('Increment'));
const text = getByTestId('count-text').props.children.join('');
A"Count: 1"
BTypeError: Cannot read property 'join' of undefined
C"Count: 0"
D"Count: undefined"
Attempts:
2 left
💡 Hint
Remember that pressing the button updates the state and the text reflects the new count.
❓ lifecycle
intermediate
2:00remaining
Which lifecycle behavior does this test verify?
Consider this test for a React Native component that fetches data on mount. What lifecycle behavior is being tested?
React Native
import React from 'react';
import { Text } from 'react-native';
import { render, waitFor } from '@testing-library/react-native';

function DataFetcher({ fetchData }) {
  const [data, setData] = React.useState(null);
  React.useEffect(() => {
    fetchData().then(setData);
  }, [fetchData]);
  return <Text>{data ?? 'Loading...'}</Text>;
}

const mockFetch = () => Promise.resolve('Hello');
const { getByText } = render(<DataFetcher fetchData={mockFetch} />);
await waitFor(() => getByText('Hello'));
AComponentWillUnmount cleans up fetchData call
BComponentDidMount triggers fetchData and updates state asynchronously
CComponentDidUpdate triggers fetchData on every render
DComponentDidCatch handles fetchData errors
Attempts:
2 left
💡 Hint
Look at when fetchData is called inside useEffect.
📝 Syntax
advanced
2:00remaining
What error does this test code produce?
Identify the error when running this React Native Testing Library code snippet.
React Native
import React from 'react';
import { Text } from 'react-native';
import { render } from '@testing-library/react-native';

const { getByText } = render(<Text>Hello</Text>);
getByText('Hello').props.onPress();
ATypeError: getByText(...).props.onPress is not a function
BReferenceError: Text is not defined
CSyntaxError: Unexpected token <
DNo error, runs successfully
Attempts:
2 left
💡 Hint
Check if all components are imported correctly.
❓ navigation
advanced
2:00remaining
What will this test verify about navigation?
Given this test for a React Navigation screen, what behavior does it check?
React Native
import React from 'react';
import { Button } from 'react-native';
import { render, fireEvent } from '@testing-library/react-native';

function HomeScreen({ navigation }) {
  return <Button title="Go" onPress={() => navigation.navigate('Details')} />;
}

const mockNavigate = jest.fn();
const { getByText } = render(<HomeScreen navigation={{ navigate: mockNavigate }} />);
fireEvent.press(getByText('Go'));
expect(mockNavigate).toHaveBeenCalledWith('Details');
AThe test ensures navigation.goBack is called on button press
BThe test verifies the Details screen is rendered after button press
CThe test checks if pressing the button calls navigation.navigate with 'Details'
DThe test confirms navigation.reset is called with empty routes
Attempts:
2 left
💡 Hint
Look at what mock function is called when the button is pressed.
🔧 Debug
expert
2:00remaining
Why does this test fail with a timeout?
This test tries to wait for a text update but fails with a timeout error. Why?
React Native
import React from 'react';
import { Text, Button } from 'react-native';
import { render, fireEvent, waitFor } from '@testing-library/react-native';

function AsyncButton() {
  const [text, setText] = React.useState('Start');
  const onPress = () => {
    setTimeout(() => setText('Done'), 1000);
  };
  return <><Text>{text}</Text><Button title="Press" onPress={onPress} /></>;
}

const { getByText } = render(<AsyncButton />);
fireEvent.press(getByText('Press'));
await waitFor(() => getByText('Done'), { timeout: 500 });
AThe getByText selector is case sensitive and misses 'Done'
BThe setTimeout callback never runs because of missing cleanup
CThe fireEvent.press does not trigger onPress handler
DThe waitFor timeout is too short to catch the delayed text update
Attempts:
2 left
💡 Hint
Compare the setTimeout delay with the waitFor timeout.

Practice

(1/5)
1. What is the main purpose of React Native Testing Library?
easy
A. To compile React Native code faster
B. To style components automatically
C. To test UI components by simulating user interactions
D. To deploy apps to app stores

Solution

  1. Step 1: Understand the library's goal

    React Native Testing Library focuses on testing UI as a user would, not on compiling or styling.
  2. Step 2: Match purpose with options

    Only To test UI components by simulating user interactions describes testing UI with user interaction simulation.
  3. Final Answer:

    To test UI components by simulating user interactions -> Option C
  4. Quick Check:

    Testing UI = B [OK]
Hint: Testing library simulates user actions, not builds or styles [OK]
Common Mistakes:
  • Confusing testing with building or styling
  • Thinking it deploys apps
  • Assuming it compiles code
2. Which of the following is the correct way to import the render function from React Native Testing Library?
easy
A. import * as render from 'react-native-testing-library';
B. import render from 'react-native-testing-library';
C. import { render } from 'react-native-testing-library/react';
D. import { render } from 'react-native-testing-library';

Solution

  1. Step 1: Recall correct import syntax

    The render function is a named export, so it must be imported with curly braces.
  2. Step 2: Check each option

    import { render } from 'react-native-testing-library'; uses named import correctly. import render from 'react-native-testing-library'; imports default which is incorrect. import { render } from 'react-native-testing-library/react'; adds extra path which is invalid. import * as render from 'react-native-testing-library'; imports all as render which is wrong.
  3. Final Answer:

    import { render } from 'react-native-testing-library'; -> Option D
  4. Quick Check:

    Named import with braces = A [OK]
Hint: Use curly braces for named imports like render [OK]
Common Mistakes:
  • Using default import instead of named import
  • Adding extra path in import
  • Importing all as a single object incorrectly
3. Given this test code snippet, what will be the output of the test?
const { getByText } = render(<Button title='Press me' onPress={() => {}} />);
const button = getByText('Press me');
expect(button).toBeTruthy();
medium
A. Test passes because the button with text 'Press me' exists
B. Test fails because getByText cannot find 'Press me'
C. Test throws a syntax error
D. Test fails because onPress is empty

Solution

  1. Step 1: Analyze render and getByText usage

    The Button component is rendered with title 'Press me'. getByText('Press me') finds that text in the button.
  2. Step 2: Understand expect assertion

    expect(button).toBeTruthy() checks that the button element exists, which it does.
  3. Final Answer:

    Test passes because the button with text 'Press me' exists -> Option A
  4. Quick Check:

    Element found = test passes = D [OK]
Hint: getByText finds visible text; empty onPress doesn't affect existence [OK]
Common Mistakes:
  • Thinking onPress must have code to find button
  • Confusing getByText with queryByText
  • Assuming syntax error without checking code
4. Identify the error in this test code snippet:
const { getByTestId } = render(<Text testID='greeting'>Hello</Text>);
fireEvent.press(getByTestId('greeting'));
expect(getByTestId('greeting')).toBeTruthy();
medium
A. getByTestId is not a valid query
B. fireEvent.press is used on a Text component which is not pressable
C. Missing import of fireEvent
D. testID should be testId

Solution

  1. Step 1: Check component and event compatibility

    Text component is not pressable by default, so fireEvent.press on it is invalid.
  2. Step 2: Verify other parts

    getByTestId is valid, fireEvent is assumed imported, testID is correct casing.
  3. Final Answer:

    fireEvent.press is used on a Text component which is not pressable -> Option B
  4. Quick Check:

    Press event on non-pressable = error = A [OK]
Hint: Only pressable components respond to fireEvent.press [OK]
Common Mistakes:
  • Assuming getByTestId is invalid
  • Confusing testID casing
  • Forgetting to import fireEvent (not shown here)
5. You want to test that pressing a button changes the text from 'Off' to 'On'. Which test code snippet correctly simulates this behavior?
hard
A. const { getByText } = render(<ToggleButton />); fireEvent.press(getByText('Off')); expect(getByText('On')).toBeTruthy();
B. const { getByText } = render(<ToggleButton />); fireEvent.changeText(getByText('Off')); expect(getByText('On')).toBeTruthy();
C. const { getByText } = render(<ToggleButton />); fireEvent.press(getByText('On')); expect(getByText('Off')).toBeTruthy();
D. const { getByText } = render(<ToggleButton />); fireEvent.click(getByText('Off')); expect(getByText('On')).toBeTruthy();

Solution

  1. Step 1: Identify correct event for button press

    fireEvent.press simulates a tap on a button, which is correct for toggling.
  2. Step 2: Check text change expectation

    After pressing 'Off', the text should change to 'On', so expect getByText('On') to be truthy.
  3. Step 3: Eliminate wrong events

    fireEvent.changeText is for text inputs, fireEvent.click is not valid in React Native Testing Library, pressing 'On' expecting 'Off' is reversed.
  4. Final Answer:

    Use fireEvent.press on 'Off' and expect 'On' text -> Option A
  5. Quick Check:

    fireEvent.press + text toggle = C [OK]
Hint: Use fireEvent.press to simulate taps changing UI text [OK]
Common Mistakes:
  • Using fireEvent.changeText on buttons
  • Using fireEvent.click which is web-only
  • Expecting wrong text after press
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