Last active
April 6, 2023 02:01
-
-
Save MrZenW/59e0258abca4fdba4dde4520f30adac9 to your computer and use it in GitHub Desktop.
Fix ReactDom.createPortal TypeError: parentInstance.children.indexOf is not a function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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