Last active
April 8, 2020 17:47
-
-
Save luciomartinez/8e8bda311146d106a6a615f66b07d0d3 to your computer and use it in GitHub Desktop.
Showcases of spying/mocking/stubbing that are hard to remember
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
/** | |
* When testing usage of React Router DOM library, the `BrowserRouter` component gets in the way. | |
* This component must be mocked in order to test children components such as Route. | |
* | |
* Here's the JSX rendered by the component to be tested (`AppRouter.js`): | |
* <Router> | |
* <Switch> | |
* <Route exact path="/home" component={HomePage} /> | |
* <Route ... /> | |
* </Switch> | |
* </Router> | |
* | |
* Tested versions here include: | |
* - react: 16.12.0 | |
* - react-router-dom: 5.1.2 | |
* | |
* Alternatives: https://stackoverflow.com/q/51031761/1505348 | |
*/ | |
import React from 'react'; | |
import { mount } from 'enzyme'; | |
import reactRouterDom, { MemoryRouter } from 'react-router-dom'; | |
jest.mock('./HomePage', () => { | |
return () => 'Home Page'; | |
}); | |
describe('AppRouter', () => { | |
beforeEach(() => { | |
jest.spyOn(reactRouterDom, 'BrowserRouter').mockImplementation(({children}) => children); | |
component = mount( | |
<MemoryRouter initialEntries={['/offers']}> | |
<AppRouter /> | |
</MemoryRouter> | |
); | |
}); | |
test('should render Home page on /home URL', () => { | |
component = mount( | |
<MemoryRouter initialEntries={['/home']}> | |
<AppRouter /> | |
</MemoryRouter> | |
); | |
expect(component).toHaveHTML('Home Page'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment