javascriptreactjsjestjsreact-testing-library

How to get the value of H1 tag and test it using Jest and RTL


I'm trying to test my component if it displays the right value in my h1.

Below is my component that will be tested.

  const Title = () => {
  return (
    <>
      <h1 aria-label='Title of the project'>MY RTL PROJECT</h1>
    </>
  );
};

export default Title;

and here is my test file that tries to check if my component displays "MY RTL PROJECT".

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


    describe('Checks the title component', () => {
    
        it('checks the value of the Title component', () => {
            const { getByText } = render(<Title />);
            const titleValue = getByText('MY RTL PROJECT')
            expect(titleValue).toBe('MY RTL PROJECT')
        })
    })

and here is the error: "messageParent" can only be used inside a worker

  ● Checks the title component › checks the value of the Title component

expect(received).toBe(expected) // Object.is equality

Expected: "MY RTL PROJECT"
Received: <h1 aria-label="Title of the project">MY RTL PROJECT</h1>

Solution

  • This line:

    const titleValue = getByText('MY RTL PROJECT')
    

    ...is returning you an element, not the text the element contains. So instead of this line:

    expect(titleValue).toBe('MY RTL PROJECT')
    

    ...you might want to use jest-dom toHaveTextContent():

    expect(titleValue).toHaveTextContent('MY RTL PROJECT')
    

    That said-- you are getting an element by text, then verifying it contains the text you just used to query it, so that test might not be of very high value. It might make more sense to just verify that it is there:

    const titleValue = getByText('MY RTL PROJECT')
    expect(titleValue).toBeInTheDocument();
    

    ...which is also from jest-dom.

    Also, although I cannot say with certainty, the usage of aria-label to apply text to your heading that is different than the text the heading contains seems dubious to me-- you might want to verify that that doesn't represent an accessibility anti-pattern.