Complete the code to render a button that logs a message when pressed.
import React from 'react'; import { Button, View } from 'react-native'; export default function App() { return ( <View> <Button title="Test" onPress={() => console.[1]('Button pressed')} /> </View> ); }
The console.log function prints messages to the console, which helps us see if the button press works during testing.
Complete the code to test if a component renders the correct text.
import React from 'react'; import { render } from '@testing-library/react-native'; import Greeting from './Greeting'; test('shows greeting message', () => { const { getByText } = render(<Greeting />); expect(getByText([1])).toBeTruthy(); });
The getByText function expects a string argument wrapped in quotes to find the text in the component.
Fix the error in the test by completing the missing assertion method.
import React from 'react'; import { render } from '@testing-library/react-native'; import Button from './Button'; test('button is disabled', () => { const { getByTestId } = render(<Button disabled={true} />); expect(getByTestId('btn')).[1](); });
toBeEnabled() which expects the button to be enabled.The toBeDisabled() matcher checks if the button is disabled, which matches the test description.
Fill both blanks to create a test that checks if a function is called when a button is pressed.
import React from 'react'; import { render, fireEvent } from '@testing-library/react-native'; import SubmitButton from './SubmitButton'; test('calls onSubmit when pressed', () => { const onSubmit = jest.[1](); const { getByText } = render(<SubmitButton onPress={onSubmit} />); fireEvent.[2](getByText('Submit')); expect(onSubmit).toHaveBeenCalled(); });
jest.mock() is incorrect here; the correct jest function to create a mock function is jest.fn(). The event to simulate a button press in React Native testing library is fireEvent.press().
So the correct answers are jest.fn() and fireEvent.press().
Fill all three blanks to write a test that checks if a text input updates its value correctly.
import React from 'react'; import { render, fireEvent } from '@testing-library/react-native'; import TextInputComponent from './TextInputComponent'; test('updates text input value', () => { const { getByPlaceholderText } = render(<TextInputComponent />); const input = getByPlaceholderText([1]); fireEvent.[2](input, { target: { [3]: 'Hello' } }); expect(input.props.value).toBe('Hello'); });
The placeholder text is a string, so it needs quotes. The correct fireEvent method for text input in React Native is changeText. The event object uses the property value to set the new text.