Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Enzyme Jest test component with className

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...

like image 768
Phil Lucks Avatar asked Mar 21 '18 17:03

Phil Lucks


People also ask

How do you get a component by className in React testing library?

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.

Can a React component have a className?

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> .


1 Answers

as per Enzyme doc you can do as below:

const wrapper = shallow(<VisitorShortcut />);
expect(wrapper.find("div.visitor-shortcuts").length).toBe(1)
like image 178
Pramod Avatar answered Oct 23 '22 04:10

Pramod