From fc5340027a2ed98309872063d7c8af2e98eb7cca Mon Sep 17 00:00:00 2001 From: Mike Deverell Date: Fri, 26 Oct 2018 22:03:09 -0400 Subject: [PATCH] [fixed] Allow ReactDOM.createPortal to be mocked in tests Fixes #553 - PR #701 * Allow ReactDOM.createPortal to be mocked in tests (9cd0891) * add testability tests (6a67946) * linting (f29e7b0) * more linting (5992f97) --- specs/Modal.testability.spec.js | 20 ++++++++++++++++++++ specs/index.js | 2 ++ src/components/Modal.js | 10 +++++++--- 3 files changed, 29 insertions(+), 3 deletions(-) create mode 100644 specs/Modal.testability.spec.js diff --git a/specs/Modal.testability.spec.js b/specs/Modal.testability.spec.js new file mode 100644 index 00000000..4b162ed8 --- /dev/null +++ b/specs/Modal.testability.spec.js @@ -0,0 +1,20 @@ +/* eslint-env mocha */ +import ReactDOM from "react-dom"; +import sinon from "sinon"; +import { mcontent, renderModal, emptyDOM } from "./helper"; + +export default () => { + afterEach("cleaned up all rendered modals", emptyDOM); + + it("renders as expected, initially", () => { + const modal = renderModal({ isOpen: true }, "hello"); + mcontent(modal).should.be.ok(); + }); + + it("allows ReactDOM.createPortal to be overridden in real-time", () => { + const createPortalSpy = sinon.spy(ReactDOM, "createPortal"); + renderModal({ isOpen: true }, "hello"); + createPortalSpy.called.should.be.ok(); + ReactDOM.createPortal.restore(); + }); +}; diff --git a/specs/index.js b/specs/index.js index b9e03b91..2d7b0dee 100644 --- a/specs/index.js +++ b/specs/index.js @@ -4,8 +4,10 @@ import ModalState from "./Modal.spec"; import ModalEvents from "./Modal.events.spec"; import ModalStyle from "./Modal.style.spec"; import ModalHelpers from "./Modal.helpers.spec"; +import ModalTestability from "./Modal.testability.spec"; describe("State", ModalState); describe("Style", ModalStyle); describe("Events", ModalEvents); describe("Helpers", ModalHelpers); +describe("Testability", ModalTestability); diff --git a/src/components/Modal.js b/src/components/Modal.js index 7a9a959b..498f8467 100644 --- a/src/components/Modal.js +++ b/src/components/Modal.js @@ -11,9 +11,11 @@ export const portalClassName = "ReactModalPortal"; export const bodyOpenClassName = "ReactModal__Body--open"; const isReact16 = ReactDOM.createPortal !== undefined; -const createPortal = isReact16 - ? ReactDOM.createPortal - : ReactDOM.unstable_renderSubtreeIntoContainer; + +const getCreatePortal = () => + isReact16 + ? ReactDOM.createPortal + : ReactDOM.unstable_renderSubtreeIntoContainer; function getParentElement(parentSelector) { return parentSelector(); @@ -180,6 +182,7 @@ class Modal extends Component { }; renderPortal = props => { + const createPortal = getCreatePortal(); const portal = createPortal( this, , @@ -197,6 +200,7 @@ class Modal extends Component { this.node = document.createElement("div"); } + const createPortal = getCreatePortal(); return createPortal(