Last active
April 28, 2022 05:45
-
-
Save HichamBenjelloun/35af93a25a94b8dd4e166cd049f1ba8b to your computer and use it in GitHub Desktop.
Testing Ionic React routing
This file contains hidden or 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 { render, screen } from '@testing-library/react'; | |
import { createMemoryHistory } from 'history'; | |
import { IonRedirect, IonRoute, IonRouterOutlet } from '@ionic/react'; | |
import { IonReactRouter } from '@ionic/react-router'; | |
import '@testing-library/jest-dom'; | |
// Using `IonRouterOutlet` here will make `jsdom` render the following DOM tree: | |
// <body> | |
// <div> | |
// <ion-router-outlet /> | |
// </div> | |
// </body> | |
// | |
// Problem: the inner routes are not rendered. | |
// | |
// A solution to this is to replace `@ionic/react` router components | |
// by their equivalents within the `react-router-dom` library. | |
jest.mock('@ionic/react', () => { | |
const { Router, Switch, Route, Redirect } = jest.requireActual('react-router-dom'); | |
return { | |
...jest.requireActual('@ionic/react'), | |
IonReactRouter: Router, | |
IonRouterOutlet: Switch, | |
IonRoute: Route, | |
IonRedirect: Redirect, | |
}; | |
}); | |
describe('routes', () => { | |
it('should work', async () => { | |
const MyRoutes = () => ( | |
<IonRouterOutlet> | |
<IonRoute exact path='/' render={() => <div>Home</div>} /> | |
<IonRoute exact path='/about' render={() => <div>About</div>} /> | |
<IonRedirect from='*' to='/about' /> | |
</IonRouterOutlet> | |
); | |
const history = createMemoryHistory(); | |
render( | |
<IonReactRouter history={history}> | |
<MyRoutes /> | |
</IonReactRouter>, | |
); | |
expect(await screen.findByText(/home/i)).toBeInTheDocument(); | |
history.push('/unknown'); | |
expect(await screen.findByText(/about/i)).toBeInTheDocument(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment