[英]How to mock a click event on an element in React using jest , react-testing-library
My component renders the following我的组件呈现以下内容
{list.options && list.options.length > 0 ? (
<div
data-testId="MyAlertText" onClick={onAddText}>
Add Text
</div>
) : null}
And, in my tests I am doing the following而且,在我的测试中,我正在执行以下操作
it('Add Text link should render', () => {
const { container, getByTestId} = render(<MyComp />);
const link = getByTestId('MyAlertText');
expect(link).toBeInTheDocument();
})
It runs successfully它运行成功
But when I try to run, and simulate onClick
it fails.但是当我尝试运行并模拟
onClick
时它失败了。
it('Add Text link should call method', () => {
const { container, getByTestId} = render(<MyComp />);
const link = getByTestId('MyAlertText');
expect(link).toBeInTheDocument();
fireEvent.click(link );
expect(jest.fn()).toHaveBeenCalled();
})
I tried mocking the function using jest mock
.我使用
jest mock
尝试了 mocking function 。 What did I do wrong?我做错了什么?
link.simulate('click') - should to the job! link.simulate('click') - 应该去工作!
Generally, you shouldn't worry about testing methods inside your component.通常,您不必担心组件内部的测试方法。 Rather, you should test the side effects of those methods.
相反,您应该测试这些方法的副作用。
Of course onAddText
will be called (or whatever onAddText
references), but what does onAddText
actually do?当然会调用
onAddText
(或任何onAddText
引用),但onAddText
实际上做了什么? Test that effect.测试那个效果。
You can use shallow
in jest to resolve your case.您可以开玩笑地使用
shallow
来解决您的问题。
it('Add Text link should render', async () => {
const wrapper = shallow(<MyComp />);
const spy = jest.spyOn(wrapper.instance(), 'onAddText');
wrapper.find('#MyAlertText).simulate('click');
await wrapper.update();
expect(spy).toHaveBeenCalled();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.