Home > Mobile >  react-testing-library check founded element tag
react-testing-library check founded element tag

Time:06-27

I want to compare founded element's tag. Which query should i use?

App.js

function App() {
  return (
    <div className="App">
      <h1>Hello World</h1>
    </div>
  );
}

export default App;

App.test.js

import { render, screen } from '@testing-library/react';
import App from './App';

test('is hello world inside the h1 tag', () => {
  render(<App />);
  const titleElement = screen.getByText(/Hello world/i);
  /* I want to check titleElement as h1 tag */
  expect(titleElement)...
});

CodePudding user response:

I found a solution like this

expect(titleElement.tagName.toLowerCase()).toBe("h1")

CodePudding user response:

You can convert it into a one-liner using React Testing library API:

expect(getByRole('heading', { level: 1, name: '/Hello world/i' })).toBeInTheDocument();
  • Related