簡體   English   中英

單擊時測試按鈕 - 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM