Skip to content

Instantly share code, notes, and snippets.

@nerfologist
Last active February 9, 2017 13:24
Show Gist options
  • Save nerfologist/130701ea81f685d898ccd60a8c37cb72 to your computer and use it in GitHub Desktop.
Save nerfologist/130701ea81f685d898ccd60a8c37cb72 to your computer and use it in GitHub Desktop.
Stub router context in tests
import React, { Component, PropTypes } from 'react';
/*
* provide a component with a stubbed router context; optionally
* pass your own stubs such as jest.fn() to check that they are called
* modern version of https://gist.github.com/jaketrent/f68028eedd4f1ddf7997
* HOC technique by Rem Zolotykh from https://youtu.be/q5OmQvh4R3s
* all credit goes to the original poster
* */
const stubRouterContext = (ComposedComponent, stubs) => {
class StubRouterContext extends Component {
getChildContext() {
return {
router: Object.assign({
push: () => {},
replace: () => {},
go: () => {},
goBack: () => {},
goForward: () => {},
setRouteLeaveHook: () => {},
isActive: () => {},
createHref: () => {}
}, stubs)
};
}
render() {
return (
<ComposedComponent {...this.props} />
);
}
}
StubRouterContext.childContextTypes = {
router: PropTypes.object
};
return StubRouterContext;
};
export default stubRouterContext;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment