javascript / beginner
Snippet
Simulating Button Click Events in Component Tests
Component tests verify user interactions by rendering components in a virtual DOM and firing synthetic events. 'fireEvent.click' simulates user clicks and triggers internal state updates for assertion.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { render, fireEvent } from '@testing-library/react';import React, { useState } from 'react';function Counter() {const [val, setVal] = useState(0);return <button onClick={() => setVal(val + 1)}>Count: {val}</button>;}test('increments value on user click', () => {const { getByText } = render(<Counter />);const button = getByText('Count: 0');fireEvent.click(button);expect(button.textContent).toBe('Count: 1');});
react
Breakdown
1
const { getByText } = render(<Counter />);
Renders the Counter component and extracts the helper method to query elements by visible text.
2
fireEvent.click(button);
Simulates a user click event on the targeted button element.
3
expect(button.textContent).toBe('Count: 1');
Asserts that the text content of the button updated to reflect the incremented counter state.