How to test if element exists?

Ask*_*Men 5 reactjs react-testing-library

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;
Run Code Online (Sandbox Code Playgroud)

For that test i created:

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

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

Boj*_*mić 22

只是关于如何稍微改进这一点的简短说明。而不是使用toBeTruthy() jest-dom实用程序库提供的.toBeInTheDocument()匹配器,它可用于断言某个元素是否在文档正文中。在这种情况下,这可能比断言真实性更有意义。

此外,最好按角色而不是文本获取按钮,因为按优先级这是更好的方式。

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


Yoa*_*azo 12

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()
});
Run Code Online (Sandbox Code Playgroud)


roo*_*der 6

我建议更好的测试方法是使用元素的“data-testid”属性

<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();
});
Run Code Online (Sandbox Code Playgroud)

我这样做的原因是 getByText 对于页面中出现的任何“增加”一词都是 true

  • getByTestId 应尽可能少地使用 https://testing-library.com/docs/guide-which-query (5认同)