Alright I have a component called <TestButton />
. Inside the <TestButton />
there are two Semantic UI React component, <Button />
and <Header>
.
Basically, when the <Button>
is clicked, it toggles display: none;
to <Header>
.
I want to check (I want to learn) on how to assert <Header>
's display: none;
when <Button>
is clicked.
TestButton.js
const TestButton = (props) => {
return (
<div id='test-button'>
<Header id='please-hide-me' size='huge'>Please Hide Me</Header>
<Button
onClick={
() => {
hiding = !hiding;
let findDOM = document.getElementById(searchForThisID);
if (findDOM) { findDOM.style.display = hiding ? 'none' : ''; }
return hiding;
}
}
>
Sample Toggle
</Button>
</div>
);
};
My unit test is based on How to test style for a React component attribute with Enzyme. It looks like this:
test(`
`, () => {
const wrapper = shallow(<TestButton />);
const button = wrapper.find('Button');
const header = wrapper.find('Header');
const headerStyle = header.get(0).style;
expect(headerStyle).to.have.property('display', '');
wrapper.find('Button').simulate('click');
expect(headerStyle).to.have.property('display', 'none');
}
);
But it has this error:
TypeError: Cannot read property 'have' of undefined
What should I do?
There are a few mistakes in your provided code:
You should not be using DOM element's style property because React does not manage it. Shift the
hidden
property into thestate
instead.I believe
headerStyle
is a shallow copy of the style object. After you simulate click, it does not get updated. You will have to query the element again for the style object.to.have.property
is not valid Jest syntax. It should betoHaveProperty
.Please refer to the corrected code here. If you paste the following into
create-react-app
, it should just work.app.js
app.test.js