如何测试元素是否存在?

How to test if element exists?

我想检查我的组件中是否存在按钮。

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;

对于我创建的那个测试:

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

在 运行 测试后我得到了 TypeError: button.toBeTruthy is not a function。 为什么会出现这个错误,如何解决?

你打错了; toBeTruthy() 不是来自按钮的函数,而是来自 expect 方法的函数。

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

我建议更好的测试方法是使用元素的“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();
});

我这样做的原因是 getByText 对于页面中出现的任何单词 Increase 都是正确的

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

此外,最好按角色而不是文本来获取按钮,因为 priority 是更可取的方式。

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