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?
TestButtoncomponent looks like?