DEV Community

Cui Mingda
Cui Mingda

Posted on

How to simulate clicking a button in Testing Library

引入user-event

import userEvent from '@testing-library/user-event'
Enter fullscreen mode Exit fullscreen mode

锁定一个按钮,直接触发click事件

const { queryByTestId } = render(<App />);
const increaseButton = queryByTestId('increase-button');
userEvent.click(increaseButton)
Enter fullscreen mode Exit fullscreen mode

触发以后,就可以测试点击以后的效果了,比如在这个例子里,点击了+1按钮,结果区域就会数值上加1。

const result = queryByTestId('result');
expect(result.textContent).toBe('1');
Enter fullscreen mode Exit fullscreen mode

对应的按钮

// JavaScript
const [result, setResult] = useState(0);

// HTML
<button data-testid="increase-button" onClick={() => setResult(result+1)}>+1</button>
Enter fullscreen mode Exit fullscreen mode

References

Top comments (0)