React is a JavaScript library which is developed by Facebook. Meta used React to build the Instagram.com website. One of the advantages of using React is that it allows frontend and web developers to quickly create user interfaces (UI) for websites.
In this article we'll go over the possibilities to test React based websites, using the React Testing Library and Selenium.
What is React Testing Library?
React Testing Library was built specifically to test React components. It builds on top of the DOM Testing Library and adds APIs to test any React component. It is a light-weight solution to create tests, with an emphasis on creating maintainable tests. It is mostly run using Jest, but can be used with other test libraries, provided you install jsdom
and global-jsdom
.
Several functions are added on top of react-dom
and react-dom/test-utils
, encouraging best testing practices.
The library, which is a replacement for Enzyme, adds methods to locate elements in the DOM by using a data-testid
attribute.
To install React Testing Library, simply execute the following command:
How can I write a React test?
Once you've installed React Testing Library, you can quickly add your very first test, either in Javascript or Typescript. See the example below, where we'll render a React component, perform various actions and finally verify the outcome.
import {render, screen} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import '@testing-library/jest-dom'
import Fetch from './fetch'
test('displays pricing', async () => {
// ARRANGE
render(<fetch url="/pricing"></fetch>)
// ACT
await userEvent.click(screen.getByText('Purchase'))
await screen.findByRole('heading')
// ASSERT
expect(screen.getByRole('heading')).toHaveTextContent('thank you')
expect(screen.getByRole('button')).toBeDisabled()
})
In the example above, we'll open the Pricing page, click on Purchase and verify if there was a thank you message.
How can I use Selenium to test React websites?
Selenium is an open-source testing framework, capable of running browser tests against any website. For Selenium to run tests on your websites, it does not matter whether it is created with PHP, Ruby on Rails, NextJS or React.
Below is an example on how to run a Selenium test against a website built with React.
const webdriver = require('selenium-webdriver');
const capabilities = {
'platform' : 'WIN10',
'browserName' : 'chrome',
'version' : 'latest',
'name': 'NodeJS Sample Test'
}
async function runTest () {
let driver = new webdriver.Builder()
.usingServer('https://hub.testingbot.com/wd/hub')
.withCapabilities(capabilities)
.build();
await driver.get("https://react.dev/");
try {
await driver.wait(webdriver.until.titleMatches(/React/i), 5000);
} catch (e) {
console.error(e)
}
await driver.quit();
}
runTest();
The code example above will start a Chrome browser session on Windows 10, navigate to the React documentation website and verify if the title of the page is correct.