Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: 'TypeError: ReactWrapper can only wrap valid elements' when using enzyme.mount

I'm getting this error when passing a React element to 'mount' function:

it("Book - move book to a shelf should work", () => {
    let test = (<Book book={book} />);
    let component = mount(test);
    const select = component.find("select").first();
    expect(select).toBeDefined();

However, if I remove the variable and pass the element directly to the method, it works.

it("Book - move book to a shelf should work", () => {
    let component = mount(<Book book={book} />);
    const select = component.find("select").first();
    expect(select).toBeDefined();

How are they different?

UPDATE: For some reason, this method (renderer.create from Jest) doesn't complain about that:

let component = renderer.create(<Book onMoveBook={onMoveBook} book={book} />);
const tree = component.toJSON(); // Works fine.

Also, surprisingly, converting the variable to a function and passing it to React.createElement worked:

var test = React.createElement(() => <Book onMoveBook={onMoveBook} book={book} />);
let component = mount(test);
like image 872
Nour Avatar asked Nov 23 '18 22:11

Nour


1 Answers

Had the same error. The error is caused by how you are mounting your 'test' component. The way you are doing it, you are not mounting a valid component, but just a variable. You want to put your variable between the < /> to make it a component.

You are doing let component = mount(test); while you should be doing let component = mount(<test/>);

like image 59
Nelly Sugu Avatar answered Sep 19 '22 02:09

Nelly Sugu