Reputation: 5182
I'm making the switch from using enzyme
to react-testing-library
for testing my components.
I have a simple component CustomModal
which acts much like a wrapper around the Modal
from reactstrap
. I am trying to test that my CustomModal
includes the child elements that it ought to.
Taking my cues from this article and this article, I am adding data-testid
attributes to my children, and then I am using getByTestId
and queryByTestId
. But, for some reason, my queries are not finding the child nodes that, as far as I can tell, are there.
Is there something I am doing wrong in my test setup, or am I misunderstanding how react-testing-library
should be used?
The basic code, along with the test (which is failing), can be found in this CodeSandbox:
My basic CustomModal
component looks like this:
/*
* src/components/CustomModal/index.js
*/
import React from "react";
import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from "reactstrap";
const getSanitizedModalProps = props => {
let modalProps = { ...props };
delete modalProps.onConfirm;
delete modalProps.onCancel;
delete modalProps.headerText;
delete modalProps.children;
modalProps.isOpen = modalProps.isOpen === true;
return modalProps;
};
export default props => {
return (
<Modal data-testid="modal" {...getSanitizedModalProps(props)}>
<ModalHeader data-testid="modal-header">{props.headerText}</ModalHeader>
<ModalBody data-testid="modal-body">{props.children}</ModalBody>
<ModalFooter data-testid="modal-footer">
<Button data-testid="confirm-button" onClick={props.onConfirm}>
Confirm
</Button>
<Button data-testid="cancel-button" onClick={props.onCancel}>
Cancel
</Button>
</ModalFooter>
</Modal>
);
};
My test file looks like this:
/*
* src/components/CustomModal/CustomModal.test.js
*/
import React from "react";
import { render } from "react-testing-library";
import CustomModal from "./index";
const TEST_IDS = {
modal: "modal",
header: "modal-header",
body: "modal-body",
footer: "modal-footer",
cancel: "cancel-button",
confirm: "confirm-button"
};
describe("<Modal />", () => {
const headerText = "hello world";
it("renders all of the children", () => {
const { queryByTestId } = render(<CustomModal headerText={headerText} />);
// The following assertions all fail
expect(queryByTestId(TEST_IDS.modal)).toBeTruthy();
expect(queryByTestId(TEST_IDS.header)).toBeTruthy();
expect(queryByTestId(TEST_IDS.body)).toBeTruthy();
expect(queryByTestId(TEST_IDS.footer)).toBeTruthy();
expect(queryByTestId(TEST_IDS.cancel)).toBeTruthy();
expect(queryByTestId(TEST_IDS.confirm)).toBeTruthy();
});
});
Upvotes: 3
Views: 8998
Reputation: 26988
Your modal is closed, you need to pass isOpen
to it:
render(<CustomModal headerText={headerText} isOpen />);
Upvotes: 1