การส่งเหตุการณ์และการทดสอบการโต้ตอบของผู้ใช้
ใช้ fireEvent.press และ fireEvent.changeText เพื่อจำลองการกระทำของผู้ใช้ จากนั้นตรวจสอบว่าสถานะได้รับการอัปเดตและฟังก์ชันตัวเรียกกลับถูกเรียกอย่างถูกต้อง
การส่งเหตุการณ์และการทดสอบการโต้ตอบของผู้ใช้ เป็นบทเรียน React Native Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน React Native Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Simulating User Events in Tests
Component tests become valuable when they verify how a component responds to user interactions — button presses, text input, form submission. React Native Testing Library provides the fireEvent utility to simulate these interactions in a test environment without a real device.
Simulating events is not the same as real user input — it directly calls the event handler prop of the element. But for most unit and integration tests, this is sufficient to verify that the component logic responds correctly to interactions.
fireEvent.press for Button Taps
fireEvent.press(element) simulates a tap on a TouchableOpacity, Pressable, or Button element. After pressing, assert on the expected side effects — state updates, navigation calls, or callback invocations.
Find the button first with a query like getByText or getByRole('button'), then fire the press event. The combination of query and event simulates the full user journey: find the button, tap it, verify the result.
import { render, fireEvent } from '@testing-library/react-native';
import { Counter } from '../src/components/Counter';
it('increments the count when the plus button is pressed', () => {
const { getByText } = render(<Counter />);
// Assert initial state
expect(getByText('Count: 0')).toBeTruthy();
// Simulate button press
fireEvent.press(getByText('+'));
// Assert state changed
expect(getByText('Count: 1')).toBeTruthy();
// Press again
fireEvent.press(getByText('+'));
expect(getByText('Count: 2')).toBeTruthy();
});fireEvent.changeText for TextInput
fireEvent.changeText(element, text) simulates typing in a TextInput. It calls the onChangeText prop with the provided string, which should update the component's state.
This is the correct way to simulate typing in a test. Do not try to manipulate the component's state directly — always go through the event handler to test the real data flow.
import { render, fireEvent } from '@testing-library/react-native';
import { SearchBar } from '../src/components/SearchBar';
it('calls onSearch with the typed query when submit is pressed', () => {
const mockSearch = jest.fn();
const { getByPlaceholderText, getByText } = render(
<SearchBar onSearch={mockSearch} />
);
const input = getByPlaceholderText('Search...');
// Simulate typing
fireEvent.changeText(input, 'react native');
// Simulate pressing the search button
fireEvent.press(getByText('Search'));
expect(mockSearch).toHaveBeenCalledWith('react native');
});Testing Form Validation Errors
A key test scenario for forms is verifying that validation errors appear when the user submits invalid data. Simulate submitting the form without filling in required fields, then assert that the error messages appear in the rendered output.
This test verifies both the validation logic and the UI rendering of error messages — two things that are easy to break during refactoring. It is one of the highest-value tests you can write for a form component.
it('shows an error when email is empty and form is submitted', () => {
const { getByText, getByRole, queryByText } = render(<LoginForm />);
// Initially no error
expect(queryByText('Email is required')).toBeNull();
// Submit without filling in the email field
fireEvent.press(getByRole('button', { name: 'Sign In' }));
// Error message should now appear
expect(getByText('Email is required')).toBeTruthy();
expect(queryByText('Password is required')).toBeTruthy();
});Testing Navigation Calls
When a button should navigate to another screen, mock the navigation object and assert that navigate was called with the correct screen name and params. This verifies the navigation logic without needing a full NavigationContainer in the test.
Mock useNavigation from @react-navigation/native in the test file and provide a mock navigate function. After pressing the button, assert that navigate was called correctly.
const mockNavigate = jest.fn();
jest.mock('@react-navigation/native', () => ({
...jest.requireActual('@react-navigation/native'),
useNavigation: () => ({ navigate: mockNavigate }),
}));
it('navigates to PostDetail when a post is pressed', () => {
const { getByText } = render(<PostList posts={[
{ id: '1', title: 'Hello World' }
]} />);
fireEvent.press(getByText('Hello World'));
expect(mockNavigate).toHaveBeenCalledWith('PostDetail', { postId: '1' });
});Testing with userEvent for More Realistic Interactions
RNTL v12+ includes a userEvent API that simulates more realistic user interactions than fireEvent. For example, userEvent.type(element, 'text') simulates pressing each character one at a time, which also fires focus, blur, and key press events in the correct order.
Use userEvent for scenarios where the order of events matters — like form validation that triggers on blur rather than on change. userEvent is async and requires await.
import { render, userEvent } from '@testing-library/react-native';
it('shows inline error after leaving the email field empty', async () => {
const user = userEvent.setup();
const { getByPlaceholderText, findByText } = render(<RegistrationForm />);
const emailInput = getByPlaceholderText('Email');
// Focus the field, then leave it (triggers onBlur validation)
await user.type(emailInput, '');
await user.press(getByPlaceholderText('Password')); // Focus next field
// Error appears after blur
expect(await findByText('Email is required')).toBeTruthy();
});Testing Toggle and Switch Components
For Switch components and custom toggle components, fire the valueChange event to simulate the user toggling the switch. Assert that the state updates correctly and any side effects (like persisting to storage) are triggered.
The fireEvent utility also supports fireEvent.scroll for scroll events and fireEvent(element, 'press') for generic custom event names if the component uses a different prop name than onPress.
import { render, fireEvent } from '@testing-library/react-native';
import { NotificationsSettings } from '../src/screens/NotificationsSettings';
it('toggles notifications when the switch is pressed', () => {
const mockSave = jest.fn();
const { getByTestId } = render(
<NotificationsSettings onSave={mockSave} />
);
const toggle = getByTestId('notifications-toggle');
// Simulate toggling the switch to true
fireEvent(toggle, 'valueChange', true);
expect(mockSave).toHaveBeenCalledWith({ notifications: true });
// Toggle back to false
fireEvent(toggle, 'valueChange', false);
expect(mockSave).toHaveBeenCalledWith({ notifications: false });
});Testing Async State Changes with act
When an interaction triggers a state update via a Promise (like an API call), you must wrap the interaction in act() so React can flush the updates before you make assertions. RNTL's fireEvent wraps synchronous updates in act automatically, but async state updates require explicit handling.
Use await act(async () => { ... }) when the component makes an async call in response to an event, or use findBy queries which implicitly wait for the DOM to update.
import { render, fireEvent, act, waitFor } from '@testing-library/react-native';
it('shows success message after form submission', async () => {
const { getByRole, findByText } = render(<ContactForm />);
fireEvent.press(getByRole('button', { name: 'Submit' }));
// findByText waits for the element to appear (async)
const successMsg = await findByText('Message sent successfully!');
expect(successMsg).toBeTruthy();
// Alternative: use waitFor with getByText
await waitFor(() => {
expect(getByText('Message sent successfully!')).toBeTruthy();
});
});Testing Disabled States
Buttons and inputs are often disabled during loading or when validation has not passed. Test that the disabled state is applied correctly by asserting with toBeDisabled() from jest-native, and verify that pressing a disabled button does not call the handler.
This catches bugs where a developer forgets to disable the submit button during an API call, allowing the user to submit multiple times and create duplicate data.
it('disables the submit button while loading', async () => {
const mockSubmit = jest.fn().mockReturnValue(new Promise(() => {})); // Never resolves
const { getByRole } = render(<LoginForm onSubmit={mockSubmit} />);
const emailInput = getByPlaceholderText('Email');
const passwordInput = getByPlaceholderText('Password');
fireEvent.changeText(emailInput, 'user@test.com');
fireEvent.changeText(passwordInput, 'password123');
const submitBtn = getByRole('button', { name: 'Sign In' });
fireEvent.press(submitBtn);
// Button should be disabled while the submit Promise is pending
expect(submitBtn).toBeDisabled();
expect(mockSubmit).toHaveBeenCalledTimes(1); // Not called again
});Testing Scroll Events
Test scroll-driven behaviors like load-more functionality using fireEvent.scroll. Pass a mock event object that matches the structure React Native components expect from a scroll event.
This is useful for testing onEndReached on FlatList, pull-to-refresh behavior, and any component that responds to scroll position. The event object needs nativeEvent.contentOffset and nativeEvent.contentSize.
it('loads more posts when scrolling to the bottom', () => {
const mockLoadMore = jest.fn();
const { getByTestId } = render(
<PostList posts={mockPosts} onLoadMore={mockLoadMore} />
);
const list = getByTestId('posts-list');
// Simulate scrolling to near the bottom
fireEvent.scroll(list, {
nativeEvent: {
contentOffset: { y: 900 },
contentSize: { height: 1000, width: 400 },
layoutMeasurement: { height: 100, width: 400 },
},
});
expect(mockLoadMore).toHaveBeenCalledTimes(1);
});Organizing Tests with the User Journey Pattern
The most valuable tests are those that verify an entire user flow within a single component or screen — the user journey pattern. Instead of testing each event in isolation, write one test that chains multiple interactions: fill in a form, press submit, and assert on the final state.
These integration-style component tests are slower than unit tests but catch more real bugs because they test the interactions between different parts of the component.
it('completes the login flow: type credentials, submit, show home', async () => {
const { getByPlaceholderText, getByRole, findByText } = render(
<LoginScreen />, { wrapper: NavigationWrapper }
);
// Step 1: Type email
fireEvent.changeText(getByPlaceholderText('Email'), 'alice@test.com');
// Step 2: Type password
fireEvent.changeText(getByPlaceholderText('Password'), 'secret123');
// Step 3: Submit
fireEvent.press(getByRole('button', { name: 'Sign In' }));
// Step 4: Assert navigation to home screen
expect(await findByText('Welcome, Alice!')).toBeTruthy();
});Quick Check
Test your understanding of React Native Mobile Development concepts from this lesson.
Lesson Recap
In this lesson you learned: how to use fireEvent.press and fireEvent.changeText to simulate user interactions in component tests, how to test form validation errors, navigation calls, and async state changes, and how the user journey pattern chains multiple interactions for more valuable integration-style tests. Next up we mock native modules and test async code flows in React Native.
เรียนรู้ JavaScript ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 30
- บทเรียน
- 120
คำถามที่พบบ่อย
บทเรียน “การส่งเหตุการณ์และการทดสอบการโต้ตอบของผู้ใช้” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การส่งเหตุการณ์และการทดสอบการโต้ตอบของผู้ใช้” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส React Native Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การส่งเหตุการณ์และการทดสอบการโต้ตอบของผู้ใช้”
ใช้ fireEvent.press และ fireEvent.changeText เพื่อจำลองการกระทำของผู้ใช้ จากนั้นตรวจสอบว่าสถานะได้รับการอัปเดตและฟังก์ชันตัวเรียกกลับถูกเรียกอย่างถูกต้อง คุณปฏิบัติ React Native Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน React Native Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน React Native Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “การส่งเหตุการณ์และการทดสอบการโต้ตอบของผู้ใช้” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน React Native Academy นี้ได้ไหม
ได้ บทเรียน React Native Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การตั้งค่า Jest ในโปรเจกต์ React Native
- การเรนเดอร์ส่วนประกอบด้วย React Native Testing Library
- การส่งเหตุการณ์และการทดสอบการโต้ตอบของผู้ใช้
- การจำลองโมดูลเนทีฟและโค้ดแบบอะซิงโครนัส