Last active
February 19, 2020 22:19
-
-
Save mahowa/5be98e16920f245dd0b43a42a67f6f11 to your computer and use it in GitHub Desktop.
Next.js router mock
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
// Place in __mocks__/next/ | |
import React, { useState } from 'react'; | |
let route = ''; | |
// Set before running test | |
export const setRoute = _route => { | |
route = _route; | |
}; | |
/* | |
* Returns: | |
* { | |
* path: string | |
* params: { | |
* [string] : string | |
* } | |
* } | |
* */ | |
const urlToObj = (url = null) => { | |
const [path, queryParams = ''] = url | |
? url.split('?') | |
: window.location.href.split('?'); | |
const params = queryParams.split('&').reduce((allParams, param) => { | |
const [key, val] = param.split('='); | |
return { ...allParams, [key]: unescape(val) }; | |
}, {}); | |
return { path, params }; | |
}; | |
const escapeUrl = url => { | |
const { path, params } = urlToObj(url); | |
return `${path}?${Object.entries(params) | |
.map(([key, val]) => `${key}=${escape(val)}`) | |
.join('&')}`; | |
}; | |
const router = { | |
replace: href => | |
window.history.replaceState({}, 'Test title', escapeUrl(href)), | |
push: href => window.history.pushState({}, 'Test title', escapeUrl(href)), | |
}; | |
const Router = ({ method }) => router[method](); | |
Router.replace = router.replace; | |
Router.push = router.push; | |
export const withRouter = Component => props => { | |
const [, setRerender] = useState(); | |
const { params: query } = urlToObj(); | |
const _router = { | |
route, | |
pathname: 'mocked-path', | |
query, | |
asPath: '', | |
replace: href => { | |
router.replace(href); | |
setRerender(Math.random()); | |
}, | |
push: href => { | |
router.push(href); | |
setRerender(Math.random()); | |
}, | |
}; | |
return <Component {...props} router={_router} />; | |
}; | |
export default Router; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment