Skip to content

Instantly share code, notes, and snippets.

@luciomartinez
Last active April 8, 2020 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luciomartinez/8e8bda311146d106a6a615f66b07d0d3 to your computer and use it in GitHub Desktop.
Save luciomartinez/8e8bda311146d106a6a615f66b07d0d3 to your computer and use it in GitHub Desktop.
Showcases of spying/mocking/stubbing that are hard to remember
/**
* 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