Before diving into event testing, make sure to check out our other related articles on How to Configure Jest in Next.js and Write Your First Test Case and How to Effectively Test Input Fields in Next.js with Jest. These articles will help you set up Jest and gain a basic understanding of how testing works in Next.js.
User events like clicks, key presses, and form submissions are key to any interactive application. If these events are not properly tested, it can lead to serious usability issues, such as broken buttons or forms not submitting correctly. Event testing ensures that components respond to user input as expected, preventing bugs from reaching production.
If you haven't set up Jest in your Next.js project yet, follow our guide How to Configure Jest in Next.js and Write Your First Test Case. Once Jest is configured, you're ready to dive into event testing.
Let’s start with a basic example: testing a button click event.
import { render, fireEvent } from '@testing-library/react';
import Button from './Button'; // Assume this is your component
describe('Button component', () => {
it('triggers click event correctly', () => {
const handleClick = jest.fn();
const { getByText } = render(<Button onClick={handleClick}>Click Me</Button>);
const button = getByText('Click Me');
fireEvent.click(button);
expect(handleClick).toHaveBeenCalledTimes(1);
});
});
fireEvent.click()
method to simulate a click event on the button.onClick
function is called exactly once using expect(handleClick).toHaveBeenCalledTimes(1)
.Another common scenario is testing form submissions. Here’s how you can test a simple form:
import { render, fireEvent } from '@testing-library/react';
import Form from './Form'; // Assume this is your form component
describe('Form component', () => {
it('submits form successfully', () => {
const handleSubmit = jest.fn();
const { getByTestId } = render(<Form onSubmit={handleSubmit} />);
const form = getByTestId('form');
fireEvent.submit(form);
expect(handleSubmit).toHaveBeenCalledTimes(1);
});
});
fireEvent.submit()
method simulates the submission of the form.onSubmit
handler is called once when the form is submitted.We already covered how to test input fields in another blog post. Check out How to Effectively Test Input Fields in Next.js with Jest. However, let’s revisit it briefly for event testing purposes:
import { render, fireEvent } from '@testing-library/react';
import InputField from './InputField'; // Assume this is your input field component
describe('InputField component', () => {
it('updates value on change', () => {
const { getByLabelText } = render(<InputField label="Name" />);
const input = getByLabelText('Name');
fireEvent.change(input, { target: { value: 'John Doe' } });
expect(input.value).toBe('John Doe');
});
});
fireEvent.change()
method simulates a change in the input field's value.expect(input.value).toBe('John Doe')
.Another common event is the key press, useful for testing keyboard accessibility or shortcut functionalities in your application.
Example: Key Press Event
import { render, fireEvent } from '@testing-library/react';
import KeyPressInput from './KeyPressInput';
describe('KeyPressInput component', () => {
it('triggers key press event correctly', () => {
const handleKeyPress = jest.fn();
const { getByLabelText } = render(<KeyPressInput onKeyPress={handleKeyPress} label="Name" />);
const input = getByLabelText('Name');
fireEvent.keyPress(input, { key: 'Enter', code: 13, charCode: 13 });
expect(handleKeyPress).toHaveBeenCalledTimes(1);
});
});
fireEvent.keyPress()
simulates a key press.key
, code
, and charCode
properties.Testing mouse events like hovering is important for components that reveal information on hover, like tooltips or dropdown menus.
import { render, fireEvent } from '@testing-library/react';
import HoverComponent from './HoverComponent';
describe('HoverComponent', () => {
it('triggers mouse over event correctly', () => {
const handleMouseOver = jest.fn();
const { getByText } = render(<HoverComponent onMouseOver={handleMouseOver}>Hover over me</HoverComponent>);
const element = getByText('Hover over me');
fireEvent.mouseOver(element);
expect(handleMouseOver).toHaveBeenCalledTimes(1);
});
});
fireEvent.mouseOver()
method simulates hovering the mouse over the element.onMouseOver
handler is called once when the hover event is triggered.Avoid Testing Internal Implementation: Focus on testing the component’s behavior, not how the event is implemented internally.
Use fireEvent
and userEvent
as Needed: While fireEvent
is useful, sometimes @testing-library/user-event
provides a more realistic simulation of user interactions.
Mocking Event Handlers: Use Jest's jest.fn()
to create mock event handlers and assert how they are called during tests.
Testing events in Next.js using Jest is essential for ensuring that user interactions, such as clicks, key presses, and hovers, work as expected. By following the examples in this guide, you can thoroughly test a variety of events in your components, improving the reliability of your application.
For more detailed insights into testing in Next.js, don't forget to check out our other articles:
Happy Testing!