Steps to implement Testing in React App
Step 1: create a new React application using Create React App
npx create-react-app app
cd app
Step 2: Install React Testing Library and any additional testing dependencies:
npm install --save-dev @testing-library/react @testing-library/jest-dom
Step 3: add MyComponent.js and MyComponent.test.js in the src directory.
Example: Below is the code example:
// MyComponent.js
import React from 'react';
const MyComponent = ({ onClick }) => {
return (
<div>
<button onClick={onClick}>
Click Me
</button>
</div>
);
};
export default MyComponent;
// MyComponent.test.js
import React from 'react';
import {
render,
screen,
fireEvent
} from '@testing-library/react';
import MyComponent from './MyComponent';
// Test to ensure that the button renders with the correct text
test('renders a button with correct text', () => {
render(<MyComponent />);
const buttonElement =
screen.getByRole('button', { name: /click me/i });
expect(buttonElement).toBeInTheDocument();
});
// Test to ensure that clicking the button triggers the provided onClick function
test('clicking button triggers onClick function', () => {
// Mock function to pass as onClick prop
const onClickMock = jest.fn();
// Render MyComponent with the mocked onClick function
render(<MyComponent onClick={onClickMock} />);
// Find the button element
const buttonElement =
screen.getByRole('button', { name: /click me/i });
// Simulate a click on the button
fireEvent.click(buttonElement);
// Expect the onClickMock function to have been called once
expect(onClickMock).toHaveBeenCalledTimes(1);
});
Step 4: Execute your tests using a test runner like Jest
npm test
Output:
What are queries in React Testing Library ?
In this article, we explain the concept of queries in the React Testing Library. Ensuring that components behave as expected when developing applications with React is crucial. One powerful tool for testing React components is the React Testing Library. At the heart of the React Testing Library lies the concept of queries.
Table of Content
- What is React Testing Library ?
- What are Queries?
- Features
- Steps to implement Testing in React App
- Conclusion
Contact Us