Errors and bugs are a fact of life. There’s no way to avoid them. The only thing we can do is to minimize the chances of them by:
How to quickly publish React components from any repository.
One aspect of testing is UI testing.
UI testing is a technique used to test the graphical user interface. It involves checking the screens, the different controls, etc., to ensure they work as intended under different conditions.
In this post, we’ll look at two libraries that enable us to carry out UI testing in our React application:
React-Testing-Library is a DOM-testing library developed by Kent. C Dodds. It is a replacement for Enzyme and provides light utility functions for use with react-dom.
It is targeted more at UI testing of React applications. This means that it does not only test the instances of React components but can also test the behaviors of the elements rendered by the React components. So it is an awesome library for React UI testing.
React Testing Library forces us to follow the principle:
“The more your tests resemble the way your software is used, the more the confidence they can give you.”
Snapshot testing is a feature in react-testing-feature in which we can get the snapshot of a React component and test them. This is important because we will add or update the component and might want to compare the changes.
Let’s see how we can perform UI testing on React components using react-testing-library
React-Testing-Library renders React components like a browser and we can select the elements just as we can using the DOM APIs or from the browser Inspector tab.
One way of selecting an element is via the getByText function.
This function grabs a text from the screen. It returns the text node of the text and with it, we can use it for assertations or for user interaction.
Example:
We have an App component:
import React from 'react';
function App() {
return (
<div>
React Example
</div>
);
}
export default App;
Let’s create a test file to assert that the App component renders a “React Example” text on the screen. To do we create an App.test.js file with the code:
import React from 'react';
import { render, screen } from '@testing-library/react';
import App from './App';
describe('App', () => {
test('renders App component', () => {
render(<App />);
screen.getByText('React Example');
});
});
What did we do here? We imported the React module, and also imported the render and screen from ‘@testing-library/react’. These functions are the basic functions for testing React components. render renders the React component in a virtual browser and screen is used to access the rendered DOM.
#web-development #react #front-end-development #javascript #testing