I try to test a React component containing child components. This is not a unit test - I want to simulate a click on a subcomponent and check if the result is what I expect. My setup is (schematically) as follows:
<Board />
<Row />
<Card />
... where component Board contains multiple Row components and component Row contains multiple Card components (yes, it's a board game). When clicking a Card it should flip, displaying the image (yes, it's a memorygame). So I use Enzyme's mount() on the because I want to be able to select a childcomponent of the Board.
This is the relevant rendered HTML from Chrome Developer tools Inspector tab:
Note that the Board contains Rows that contain Cards, identified by their like-named classes.
I am able to select a Card:
expect(component.find("[data-id='6'] .class")).toBeDefined()
doesn't throw error but when I simulate a click on a Card I do get an error. This is my test:
import React from "react";
import { Board } from "../components/Board";
import { mount } from "enzyme";
let component;
beforeEach(() => {
component = mount(<Board />);
console.log(component.debug());
});
describe("Test the puzzle", () => {
it("should show 1 turned card when clicked", () => {
const button = component.find(".button");
const card = component.find("div[data-id='7']");
expect(button).toBeDefined();
expect(card).toBeDefined();
button.simulate("click");
card.simulate("click");
});
});
This gives the errors
● Test the puzzle › should show 1 turned card when clicked
Method “simulate” is meant to be run on 1 node. 0 found instead.
44 | expect(card).toBeDefined();
45 | button.simulate("click");
> 46 | card.simulate("click");
| ^
47 | });
48 | });
49 |
The debugging() output of the the Board shows a shallow mount: Board contains a Row but Row does not contain Cards:
<Board>
<div className="container">
<div className="board">
<Row cards={{...}} onClick={[Function: onClickCard]} updateCardReference={[Function: updateCardReference]}>
<div className="row" />
</Row>
So that leads me to believe there's nothing wrong with my selecting DOM elements but Enzyme's mount() is doing a shallow mount instead.
What do you think?
"react": "^16.13.1", "react-dom": "^16.13.1", "@testing-library/jest-dom": "^5.11.5", "enzyme": "^3.11.0", "enzyme-adapter-react-16": "^1.15.5",
