单击时测试按钮 - React 测试库
Test button when it is clicked - React testing library
我正在为单击时的增量按钮编写一个测试用例。
function App() {
const [count, setCount] = useState(0);
const handleIncrement = () => {
if(count >= 0){
setCount(count + 1);
}
}
const handleDecrement = () => {
if(count > 0){
setCount(count - 1);
}
}
return (
<div>
Count : {count}
</div>
<div>
<button onClick={handleIncrement}>Increment</button>
<button onClick={handleDecrement}>Decrement</button>
</div>
</div>
);
}
下面是给我错误提示 Matcher error: received value must be a mock or spy function
的测试用例
当点击事件被触发时,如何期望按钮被点击。有人可以帮忙吗?
it('should handle count increment', ()=>{
render(<App />);
const incrementButton = screen.getByRole('button',{name: 'Increment'})
fireEvent.click(incrementButton)
expect(incrementButton).toHaveBeenCalled()
})
正如 jonrsharpe 在他的评论中指出的那样,测试库的精神是在可见的用户界面而不是实现细节上进行测试。因此,您不是要测试按钮是否被单击,而是要测试单击按钮的结果是可见计数增加 1。
换句话说,测试用户操作的结果应该是什么,而不是用户操作发生了。
因此,对于您的增量器,以下是一个很好的断言示例:
expect(screen.queryByText('Count : 1')).toBeInTheDocument()
我正在为单击时的增量按钮编写一个测试用例。
function App() {
const [count, setCount] = useState(0);
const handleIncrement = () => {
if(count >= 0){
setCount(count + 1);
}
}
const handleDecrement = () => {
if(count > 0){
setCount(count - 1);
}
}
return (
<div>
Count : {count}
</div>
<div>
<button onClick={handleIncrement}>Increment</button>
<button onClick={handleDecrement}>Decrement</button>
</div>
</div>
);
}
下面是给我错误提示 Matcher error: received value must be a mock or spy function
的测试用例
当点击事件被触发时,如何期望按钮被点击。有人可以帮忙吗?
it('should handle count increment', ()=>{
render(<App />);
const incrementButton = screen.getByRole('button',{name: 'Increment'})
fireEvent.click(incrementButton)
expect(incrementButton).toHaveBeenCalled()
})
正如 jonrsharpe 在他的评论中指出的那样,测试库的精神是在可见的用户界面而不是实现细节上进行测试。因此,您不是要测试按钮是否被单击,而是要测试单击按钮的结果是可见计数增加 1。
换句话说,测试用户操作的结果应该是什么,而不是用户操作发生了。
因此,对于您的增量器,以下是一个很好的断言示例:
expect(screen.queryByText('Count : 1')).toBeInTheDocument()