App.js file
import React from 'react';
import { Button } from 'react-bootstrap'
function App() {
return (
<div className="App">
<input type="checkbox"/>
<h1>Techstackguru</h1>
<Button data-testid="buttonId" >Search</Button>
<img width="100" height="50" alt="img-1"/>
<form action="">
<label htmlFor="user" data-testid="foo">Username</label>
<input id="user" type="text"/>
</form>
<input placeholder="placeholder-name" />
<textarea name="message">Hello World</textarea>
</div>
);
}
export default App;
App.test.js file
import { render, screen } from '@testing-library/react';
import App from './App';
import React from 'react';
// getByText
test('getByText', () => {
render(<App />);
const linkElement = screen.getByText(/Techstackguru/i);
expect(linkElement).toBeInTheDocument();
});
// getByRole
test('getByRole', () => {
render(<App />);
expect(screen.getByRole("heading")).toHaveTextContent(/Techstackguru/);
expect(screen.getByRole("button", { name: "Search" })).not.toBeDisabled();
expect(screen.getByRole("img")).toBeInTheDocument();
expect(screen.getByRole("checkbox")).toBeInTheDocument();
});
// getByLabelText
test('getByLabelText', () => {
render(<App />);
expect(screen.getByLabelText('Username')).toBeInTheDocument();
});
// getByPlaceholderText
test('getByPlaceholderText', () => {
render(<App />);
expect(screen.getByPlaceholderText('placeholder-name'));
});
// getByAltText
test('getByAltText', () => {
render(<App />);
expect(screen.getByAltText(/img-1/i));
});
// getByDisplayValue
test('getByDisplayValue', () => {
render(<App />);
expect(screen.getByDisplayValue('Hello World')).toBeInTheDocument();
});
To Run test we use below command
npm test