I am
Following both the Enzyme examples for .find() and this GitHub enzyme-example-jest example to get a basic component to test and verify the outer-most element className
exists, I do not understand why this does not pass:
// REACT COMPONENT
class VisitorShortcut extends Component {
//all the props & lifecycle hooks here
render() {
return (
<div className="visitor-shortcuts"> // <-- this className is being tested
<div
onClick={e => e.stopPropagation()}
className="dropdown open"
>
<ul
style={style}
ref="shortcutContainer"
className={"dropdown-menu "}
>
{results}
</ul>
</div>
</div>
);
}
}
// TEST FILE
import React from "react";
import { shallow, mount } from "enzyme";
import VisitorShortcut from "../VisitorShortcut";
describe("Shortcuts", () => {
test("The main Class exists", () => {
expect(
(<VisitorShortcut />).find(".visitor-shortcuts").length
).toBe(1);
});
});
// OUTPUT
Expected value to be (using ===):
1
Received:
0
if I switch to expect(wrapper.find('div.some-class')).to.have.length(3);
as per Enzyme docs, the output is TypeError: Cannot read property 'have' of undefined
I am fairly sure I do not need to use the mount
API instead of shallow
Thanks for helping to clarify this. It seems so basic...
To find elements by className in React testing library: Render a component and destructure the container object from the result. Use the getElementsByClassName() method on the container to find elements by class name.
To pass class names as props to a React component: Pass a string containing the class names as a prop. Destructure the prop in the child component. Assign the class names to an element, e.g. <h2 className={className}>Content</h2> .
as per Enzyme doc you can do as below:
const wrapper = shallow(<VisitorShortcut />);
expect(wrapper.find("div.visitor-shortcuts").length).toBe(1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With