gpt4 book ai didi

reactjs - 为什么我的按钮在我的测试中未定义?

转载 作者:行者123 更新时间:2023-11-28 20:52:07 26 4
gpt4 key购买 nike

我的测试:

  describe('button component', () => {
it('should toggle off when clicked', () => {
let component;
component = ReactTestUtils.renderIntoDocument(<Search />);
let searchbtn = ReactTestUtils.findRenderedDOMComponentWithTag(component, 'button');
ReactTestUtils.Simulate.click(searchbtn);
console.log(searchbtn, 'search button***'); //UNDEFINED
expect(searchbtn.calledOnce).to.equal(false);
})
});

这是我的搜索组件:

  render() {
return (
<div className="search">
<button className="searchButton" onClick={this.handleSearch}>{this.state.on ? 'ON' : 'OFF'}</button>
</div>
);
}

我需要监视它还是模拟它?还是有更好的方法来测试 React 中的按钮?

最佳答案

既然你已经添加了enzyme标签,我将使用enzyme来回答。

它可以通过浅层渲染很容易地进行测试-

const searchWrapper = shallow(<Search />);
const button = searchWrapper.find('button').first();

当您模拟按钮上的点击事件时,将调用通过 onClick 属性提供的 onClick 处理程序,在您的情况下是 handleSearch

因此,如果您根据 onClick 函数调用相应的 ui 更改设置某些状态,则可以比较或检查更改是否正确反射(reflect)在 dom 中。

如果你只是想通过使用类似名称的假方法来检查方法是否被调用 -

const onButtonClick = sinon.spy();
expect(onButtonClick.calledOnce).to.equal(false);
button.setProps({ onClick:onButtonClick});
button.simulate('click');
expect(onButtonClick.calledOnce).to.equal(true);

关于reactjs - 为什么我的按钮在我的测试中未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42434210/

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