Last active
February 9, 2017 13:24
-
-
Save nerfologist/130701ea81f685d898ccd60a8c37cb72 to your computer and use it in GitHub Desktop.
Stub router context in tests
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
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