Last active
May 13, 2019 09:37
-
-
Save simmo/9b8d9fb13b5fba513a76a8413eeeb805 to your computer and use it in GitHub Desktop.
React SSR hook testing
This file contains hidden or 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 { createElement } from 'react' | |
import { renderToString } from 'react-dom/server' | |
export default function renderHookServer( | |
hookInit: Function | |
): // eslint-disable-next-line @typescript-eslint/no-explicit-any | |
any { | |
let hookOutput = undefined | |
function HookWrapper() { | |
hookOutput = hookInit() | |
return createElement('div') | |
} | |
renderToString(createElement(HookWrapper)) | |
return hookOutput | |
} |
This file contains hidden or 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
/** | |
* @jest-environment node | |
*/ | |
import renderHookServer from '../../utils/renderHookServer' | |
import useMediaQuery from '.' | |
describe('useMediaQuery', () => { | |
describe('server', () => { | |
test('uses a default fallback', () => { | |
const result = renderHookServer(() => useMediaQuery('(min-width: 300px)')) | |
expect(result).toBe(false) | |
}) | |
test('uses a specific fallback', () => { | |
const result = renderHookServer(() => | |
useMediaQuery('(min-width: 300px)', true) | |
) | |
expect(result).toBe(true) | |
}) | |
}) | |
}) |
This file contains hidden or 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 { useEffect, useState } from 'react' | |
export default function useMediaQuery( | |
query: string, | |
fallback: boolean = false | |
): boolean { | |
const [state, setState] = useState(fallback) | |
// Listen for changes | |
useEffect(() => { | |
const mediaQuery = window.matchMedia(query) | |
const handleChange = ({ matches }: MediaQueryListEvent) => { | |
setState(matches) | |
} | |
mediaQuery.addListener(handleChange) | |
return () => { | |
mediaQuery.removeListener(handleChange) | |
} | |
}, [query]) | |
return state | |
} |
Looks totally legit 👍 May be a cool addition to react-hooks-testing-library
Thanks again @kentcdodds
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Jest + Node + React SSR + React hooks