Skip to content

Instantly share code, notes, and snippets.

@Cerberus
Last active May 27, 2022 05:24
Show Gist options
  • Save Cerberus/1ef9b9854f1132ae7c0e446b59359379 to your computer and use it in GitHub Desktop.
Save Cerberus/1ef9b9854f1132ae7c0e446b59359379 to your computer and use it in GitHub Desktop.
Component Testing (+ React 18) Mount via URL
import ReactDOM from 'react-dom/client'
import { MemoryRouter } from 'react-router-dom'
import { mount } from '@cypress/react'
import Application from '../Application' // NOTE: Your main component
export const open = (path: string) => {
let myRoot: ReactDOM.Root
mount(<div />, {
ReactDom: {
// @ts-ignore ignore return type
render: (_: any, rootEl: Element | null) => {
const root = ReactDOM.createRoot(rootEl!)
myRoot = root
root.render(
<MemoryRouter initialEntries={[path]}>
<Application />
</MemoryRouter>,
)
},
unmountComponentAtNode: () => {
// NOTE: Clear client-store & localStorage here to prevent side-effect to next testing
myRoot.unmount()
return true
},
},
})
}
@Cerberus
Copy link
Author

On test file

import { open } from './ct-open-by-url'
describe('Home', () => {
	it('Simple', () => {
		open('/')
	})
})

@Cerberus
Copy link
Author

pkg:

react: 18.1.0
react-router-dom: 6.3.0
@cypress/react: 5.12.4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment