2

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.

enter image description here

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 ?

1
  • Does casing matter for attributes like this? I've always used data-testid instead of data-testId Commented Aug 6, 2020 at 15:52

3 Answers 3

1

link.simulate('click') - should to the job!

Sign up to request clarification or add additional context in comments.

3 Comments

can you provide more specific, since your answer is correct.
Sorry I am new to answering on stackoverflow. My post shortly answers what the problem of the poster is? AM I supposed to provide more information that the poster need? That is how you simulate clicks with jest, I don't know what else I can add to make it more specific maybe you can enlighten me :D
This will work if you are using enzyme but not if you are using testing-library, like OP asked
1

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? Test that effect.

Comments

0

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();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.