0

I have a HTML button styled using styled component library and I am writing a unit test for it. The POC code looks like this:

const StyledButtonComponent = () => {
const [testText, setTestText] = React.useState();

const clickHandler = (e) => {
  e.preventDefault();
  setTestText('Lorem Ipsum')
  console.log('Button Clicked!');
}

return (
 <>
    <TestButton onClick={clickHandler} data-test="component-styled-button">
    Click Me!!
    </TestButton>
   <p data-test="text-tag">{testText}</p>
 </>
);
}

Here TestButton is a styled component.

And my unit test code is:

describe('Styled Button Component', () => {
let wrapper;
const setup = () => mount(<StyledButtonComponent />)
const findByAttr = (wrapper, val) => {
   return wrapper.find(`[data-test='${val}']`)
}

beforeEach(() => {
  wrapper = setup();
});

it('should render the styled button component without errors', () => {
  const btnComponent = findByAttr(wrapper, 'component-styled-button');
  expect(btnComponent).toHaveLength(2);
});

it('should allow user to click on the styled button', () => {
  const btnComponent = findByAttr(wrapper, 'component-styled-button');
  btnComponent.simulate('click', { preventDefault() {}})
  const pTag = findByAttr(wrapper, 'text-tag');
  expect(pTag.render().text()).toBe('Lorem Ipsum')
});
});

But for the second test I am getting an error:

Method “simulate” is meant to be run on 1 node. 2 found instead.

So what is the correct way to test components rendered using Styled Component?

2
  • What's your TestButton component looks like? Commented Jul 1, 2021 at 5:09
  • @slideshowp2 the look and feel of the button is as per the styles I have mentioned in my Styled Component code for the button Commented Jul 1, 2021 at 5:42

1 Answer 1

3

When you find in a wrapper of EnzymeJS, it will give you back the actual DOM element as well as React Wrapper which wraps it also.

To solve this issue, you can use multiple options. One of them is first().

const btnComponent = findByAttr(wrapper, 'component-styled-button').first();

Reference: https://enzymejs.github.io/enzyme/docs/api/ReactWrapper/first.html

Another one is at(index).

const btnComponent = findByAttr(wrapper, 'component-styled-button').at(0);

Reference: https://enzymejs.github.io/enzyme/docs/api/ReactWrapper/at.html

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

1 Comment

Thanks @Kevin for your answer. I believe this will also work when I am wrapping my components with <Provider> tag in case of redux

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.