Skip to content

Instantly share code, notes, and snippets.

@MrZenW
Last active April 6, 2023 02:01
Show Gist options
  • Save MrZenW/59e0258abca4fdba4dde4520f30adac9 to your computer and use it in GitHub Desktop.
Save MrZenW/59e0258abca4fdba4dde4520f30adac9 to your computer and use it in GitHub Desktop.
Fix ReactDom.createPortal TypeError: parentInstance.children.indexOf is not a function
import { expect } from "@jest/globals";
import React, { ReactPortal } from "react";
import ReactDom from "react-dom";
import renderer from "react-test-renderer";
import { waitFor } from "@testing-library/react";
import * as componentModule from "./TestReactDomCreatePortalTypeError";
const { TestReactDomCreatePortalTypeError } = componentModule;
describe("Test ReactDom.createPortal TypeError: parentInstance.children.indexOf is not a function", () => {
/* πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡ */
const ogCreatePortal = ReactDom.createPortal;
beforeAll(() => {
/* πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡ */
ReactDom.createPortal = jest.fn((element): ReactPortal => {
return element as ReactPortal;
});
jest.useFakeTimers();
});
afterAll(() => {
jest.useRealTimers();
/* πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡ */
ReactDom.createPortal = ogCreatePortal;
});
it("test", async () => {
const mockedFakeApiFetch = jest.spyOn(componentModule, "fakeApiFetch");
await renderer.act(async () => {
const component = renderer.create(<TestReactDomCreatePortalTypeError />);
jest.advanceTimersByTime(2000);
await waitFor(() => {
expect(mockedFakeApiFetch).toBeCalled();
});
expect(component.toJSON()).toMatchSnapshot();
});
});
});
import * as React from "react";
import { createPortal } from "react-dom";
export const fakeApiFetch = (): Promise<string> => {
return new Promise((resolve) => {
setTimeout(() => {
resolve("done");
}, 1000);
});
};
export const TestReactDomCreatePortalTypeError = (): JSX.Element => {
const [apiResult, setApiResult] = React.useState<string>(null);
React.useEffect(() => {
fakeApiFetch()
.then((res) => {
console.log("fakeApiFetch result");
setApiResult(res);
})
.catch((err) => {
console.log(err);
});
}, []);
console.log("render", apiResult);
return (
<div>
{apiResult}
{createPortal(<div>portal</div>, document.body)}
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment