How to test if element exists?

Viewed 39501

I want to check if inside my component exists a button.

import React, {useState} from 'react';

const Text = ({text}) => {
    const [state, setState]= useState(0);

    const add  = () => {
        setState(state+1)
    };

    return (
        <div>
            <h1>Hello World</h1>
            <h2>Hello {text}</h2>
            <h2>Count {state}</h2>
            <button role="button" onClick={add}>Increase</button>
        </div>
    );
};

export default Text;

For that test i created:

test('check counter', ()=> {
    const { getByText } = render(<Text />);
    const button = getByText("Increase");
    expect(button.toBeTruthy())
});

After running the test i get TypeError: button.toBeTruthy is not a function. Why this errror appears and how to solve the issue?

3 Answers

You have a mistake; The toBeTruthy() is not a function from the button is a function from the expect method.

  test('check counter', ()=> {
    const { getByText } = render(<Text />);
    const button = getByText("Increase");
    expect(button).toBeTruthy()
});

Just one short note on how to improve this a little bit. Instead of using toBeTruthy() jest-dom utility library provides the .toBeInTheDocument() matcher, which can be used to assert that an element is in the body of the document, or not. This can be more meaningful than asserting truthfulness in this case.

Also it would be better to get the button by role instead of text since it is a preferable way by priority.

  test('check counter', ()=> {
    const { getByRole } = render(<Text />);
    const button = getByRole('button');
    expect(button).toBeInTheDocument()
});

I would suggest a better way to test this would be to make use of the "data-testid" attribute for the element

<div>
            <h1>Hello World</h1>
            <h2>Hello {text}</h2>
            <h2>Count {state}</h2>
            <button role="button" data-testid="required-button" onClick={add}>Increase</button>
</div>

test('check counter', ()=> {
    const { getByTestId } = render(<Text />);
    const button = getByTestId("required-button");
    expect(button).toBeInTheDocument();
});

The reason i would do this is getByText would be true for any occurrence of the word Increase in the page

Related