gpt4 book ai didi

reactjs - 如何测试元素是否存在?

转载 作者:行者123 更新时间:2023-12-03 23:59:06 26 4
gpt4 key购买 nike

我想检查我的组件内部是否存在一个按钮。

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()
});

关于reactjs - 如何测试元素是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64946753/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com