admin管理员组文章数量:1416304
My ponent 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.
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
. What did I do wrong ?
My ponent 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.
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
. What did I do wrong ?
-
Does casing matter for attributes like this? I've always used
data-testid
instead ofdata-testId
– Attila Commented Aug 6, 2020 at 15:52
3 Answers
Reset to default 1link.simulate('click') - should to the job!
Generally, you shouldn't worry about testing methods inside your ponent. 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? Test that effect.
You can use shallow
in jest to resolve your case.
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();
});
本文标签:
版权声明:本文标题:javascript - How to mock a click event on an element in React using jest , react-testing-library - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745253948a2649987.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论