Skip to content

Commit fc53400

Browse files
devrelmdiasbruno
authored andcommittedOct 27, 2018
[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)
1 parent 6a6bcf7 commit fc53400

File tree

3 files changed

+29
-3
lines changed

3 files changed

+29
-3
lines changed
 

Diff for: ‎specs/Modal.testability.spec.js

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/* eslint-env mocha */
2+
import ReactDOM from "react-dom";
3+
import sinon from "sinon";
4+
import { mcontent, renderModal, emptyDOM } from "./helper";
5+
6+
export default () => {
7+
afterEach("cleaned up all rendered modals", emptyDOM);
8+
9+
it("renders as expected, initially", () => {
10+
const modal = renderModal({ isOpen: true }, "hello");
11+
mcontent(modal).should.be.ok();
12+
});
13+
14+
it("allows ReactDOM.createPortal to be overridden in real-time", () => {
15+
const createPortalSpy = sinon.spy(ReactDOM, "createPortal");
16+
renderModal({ isOpen: true }, "hello");
17+
createPortalSpy.called.should.be.ok();
18+
ReactDOM.createPortal.restore();
19+
});
20+
};

Diff for: ‎specs/index.js

+2
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@ import ModalState from "./Modal.spec";
44
import ModalEvents from "./Modal.events.spec";
55
import ModalStyle from "./Modal.style.spec";
66
import ModalHelpers from "./Modal.helpers.spec";
7+
import ModalTestability from "./Modal.testability.spec";
78

89
describe("State", ModalState);
910
describe("Style", ModalStyle);
1011
describe("Events", ModalEvents);
1112
describe("Helpers", ModalHelpers);
13+
describe("Testability", ModalTestability);

Diff for: ‎src/components/Modal.js

+7-3
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,11 @@ export const portalClassName = "ReactModalPortal";
1111
export const bodyOpenClassName = "ReactModal__Body--open";
1212

1313
const isReact16 = ReactDOM.createPortal !== undefined;
14-
const createPortal = isReact16
15-
? ReactDOM.createPortal
16-
: ReactDOM.unstable_renderSubtreeIntoContainer;
14+
15+
const getCreatePortal = () =>
16+
isReact16
17+
? ReactDOM.createPortal
18+
: ReactDOM.unstable_renderSubtreeIntoContainer;
1719

1820
function getParentElement(parentSelector) {
1921
return parentSelector();
@@ -180,6 +182,7 @@ class Modal extends Component {
180182
};
181183

182184
renderPortal = props => {
185+
const createPortal = getCreatePortal();
183186
const portal = createPortal(
184187
this,
185188
<ModalPortal defaultStyles={Modal.defaultStyles} {...props} />,
@@ -197,6 +200,7 @@ class Modal extends Component {
197200
this.node = document.createElement("div");
198201
}
199202

203+
const createPortal = getCreatePortal();
200204
return createPortal(
201205
<ModalPortal
202206
ref={this.portalRef}

0 commit comments

Comments
 (0)