Skip to content

Release testHook and act support #280

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 6, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .all-contributorsrc
Original file line number Diff line number Diff line change
Expand Up @@ -615,6 +615,18 @@
"contributions": [
"code"
]
},
{
"login": "donavon",
"name": "Donavon West",
"avatar_url": "https://avatars3.githubusercontent.com/u/887639?v=4",
"profile": "http://donavon.com",
"contributions": [
"code",
"doc",
"ideas",
"test"
]
}
]
}
57 changes: 34 additions & 23 deletions README.md

Large diffs are not rendered by default.

58 changes: 58 additions & 0 deletions examples/__tests__/react-hooks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* This is the recommended way to test reusable custom react hooks.
* It is not however recommended to use the testHook utility to test
* single-use custom hooks. Typically those are better tested by testing
* the component that is using it.
*/
import {testHook, act, cleanup} from 'react-testing-library'

import useCounter from '../react-hooks'

afterEach(cleanup)

test('accepts default initial values', () => {
let count
testHook(() => ({count} = useCounter()))

expect(count).toBe(0)
})

test('accepts a default initial value for `count`', () => {
let count
testHook(() => ({count} = useCounter({})))

expect(count).toBe(0)
})

test('provides an `increment` function', () => {
let count, increment
testHook(() => ({count, increment} = useCounter({step: 2})))

expect(count).toBe(0)
act(() => {
increment()
})
expect(count).toBe(2)
})

test('provides an `decrement` function', () => {
let count, decrement
testHook(() => ({count, decrement} = useCounter({step: 2})))

expect(count).toBe(0)
act(() => {
decrement()
})
expect(count).toBe(-2)
})

test('accepts a default initial value for `step`', () => {
let count, increment
testHook(() => ({count, increment} = useCounter({})))

expect(count).toBe(0)
act(() => {
increment()
})
expect(count).toBe(1)
})
10 changes: 10 additions & 0 deletions examples/react-hooks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import {useState} from 'react'

function useCounter({initialCount = 0, step = 1} = {}) {
const [count, setCount] = useState(initialCount)
const increment = () => setCount(c => c + step)
const decrement = () => setCount(c => c - step)
return {count, increment, decrement}
}

export default useCounter
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,16 @@
"jest-dom": "^2.0.4",
"jest-in-case": "^1.0.2",
"kcd-scripts": "^0.44.0",
"react": "^16.5.2",
"react-dom": "^16.5.2",
"react": "^16.8.0",
"react-dom": "^16.8.0",
"react-redux": "^5.0.7",
"react-router": "^4.3.1",
"react-router-dom": "^4.3.1",
"react-transition-group": "^2.5.0",
"redux": "^4.0.0"
},
"peerDependencies": {
"react": "*",
"react-dom": "*"
},
"eslintConfig": {
Expand Down
42 changes: 42 additions & 0 deletions src/__tests__/act.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import 'jest-dom/extend-expect'
import React from 'react'
import {render, cleanup, fireEvent} from '../'

afterEach(cleanup)

test('render calls useEffect immediately', () => {
const effectCb = jest.fn()
function MyUselessComponent() {
React.useEffect(effectCb)
return null
}
render(<MyUselessComponent />)
expect(effectCb).toHaveBeenCalledTimes(1)
})

test('fireEvent triggers useEffect calls', () => {
const effectCb = jest.fn()
function Counter() {
React.useEffect(effectCb)
const [count, setCount] = React.useState(0)
return <button onClick={() => setCount(count + 1)}>{count}</button>
}
const {
container: {firstChild: buttonNode},
} = render(<Counter />)

effectCb.mockClear()
fireEvent.click(buttonNode)
expect(buttonNode).toHaveTextContent('1')
expect(effectCb).toHaveBeenCalledTimes(1)
})

test('calls to hydrate will run useEffects', () => {
const effectCb = jest.fn()
function MyUselessComponent() {
React.useEffect(effectCb)
return null
}
render(<MyUselessComponent />, {hydrate: true})
expect(effectCb).toHaveBeenCalledTimes(1)
})
15 changes: 15 additions & 0 deletions src/__tests__/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -163,3 +163,18 @@ test('onChange works', () => {
fireEvent.change(input, {target: {value: 'a'}})
expect(handleChange).toHaveBeenCalledTimes(1)
})

test('calling `fireEvent` directly works too', () => {
const handleEvent = jest.fn()
const {
container: {firstChild: button},
} = render(<button onClick={handleEvent} />)
fireEvent(
button,
new Event('MouseEvent', {
bubbles: true,
cancelable: true,
button: 0,
}),
)
})
10 changes: 10 additions & 0 deletions src/__tests__/no-act.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import {act} from '..'

jest.mock('react-dom/test-utils', () => ({}))

test('act works even when there is no act from test utils', () => {
const callback = jest.fn()
act(callback)
expect(callback).toHaveBeenCalledTimes(1)
expect(callback).toHaveBeenCalledWith(/* nothing */)
})
9 changes: 1 addition & 8 deletions src/__tests__/render.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import 'jest-dom/extend-expect'
import React from 'react'
import ReactDOM from 'react-dom'
import {render, cleanup, flushEffects} from '../'
import {render, cleanup} from '../'

afterEach(cleanup)

Expand Down Expand Up @@ -90,10 +90,3 @@ it('supports fragments', () => {
cleanup()
expect(document.body.innerHTML).toBe('')
})

test('flushEffects can be called without causing issues', () => {
render(<div />)
const preHtml = document.documentElement.innerHTML
flushEffects()
expect(document.documentElement.innerHTML).toBe(preHtml)
})
14 changes: 14 additions & 0 deletions src/__tests__/test-hook.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import {useState} from 'react'
import 'jest-dom/extend-expect'
import {testHook, cleanup} from '../'

afterEach(cleanup)

test('testHook calls the callback', () => {
const spy = jest.fn()
testHook(spy)
expect(spy).toHaveBeenCalledTimes(1)
})
test('confirm we can safely call a React Hook from within the callback', () => {
testHook(() => useState())
})
12 changes: 12 additions & 0 deletions src/act-compat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import {act as reactAct} from 'react-dom/test-utils'

// act is supported [email protected]
// and is only needed for versions higher than that
// so we do nothing for versions that don't support act.
const act = reactAct || (cb => cb())

function rtlAct(...args) {
return act(...args)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can actually polyfill it for older versions of react

function act(fn){
  ReactDOM.unstable_batchedUpdates(fn);
  ReactDOM.render(<div/>, document.createElement('div'));
}

you won't get the warnings, but something's better than nothing I suppose.

}

export default rtlAct
54 changes: 46 additions & 8 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import React from 'react'
import ReactDOM from 'react-dom'
import {getQueriesForElement, prettyDOM, fireEvent} from 'dom-testing-library'
import {
getQueriesForElement,
prettyDOM,
fireEvent as dtlFireEvent,
} from 'dom-testing-library'
import act from './act-compat'

const mountedContainers = new Set()

Expand All @@ -20,9 +26,13 @@ function render(
mountedContainers.add(container)

if (hydrate) {
ReactDOM.hydrate(ui, container)
act(() => {
ReactDOM.hydrate(ui, container)
})
} else {
ReactDOM.render(ui, container)
act(() => {
ReactDOM.render(ui, container)
})
}
return {
container,
Expand Down Expand Up @@ -51,12 +61,17 @@ function render(
}
}

function cleanup() {
mountedContainers.forEach(cleanupAtContainer)
function TestHook({callback}) {
callback()
return null
}

function flushEffects() {
ReactDOM.render(null, document.createElement('div'))
function testHook(callback) {
render(<TestHook callback={callback} />)
}

function cleanup() {
mountedContainers.forEach(cleanupAtContainer)
}

// maybe one day we'll expose this (perhaps even as a utility returned by render).
Expand All @@ -69,6 +84,29 @@ function cleanupAtContainer(container) {
mountedContainers.delete(container)
}

// react-testing-library's version of fireEvent will call
// dom-testing-library's version of fireEvent wrapped inside
// an "act" call so that after all event callbacks have been
// been called, the resulting useEffect callbacks will also
// be called.
function fireEvent(...args) {
let returnValue
act(() => {
returnValue = dtlFireEvent(...args)
})
return returnValue
}

Object.keys(dtlFireEvent).forEach(key => {
fireEvent[key] = (...args) => {
let returnValue
act(() => {
returnValue = dtlFireEvent[key](...args)
})
return returnValue
}
})

// React event system tracks native mouseOver/mouseOut events for
// running onMouseEnter/onMouseLeave handlers
// @link https://github.com/facebook/react/blob/b87aabdfe1b7461e7331abb3601d9e6bb27544bc/packages/react-dom/src/events/EnterLeaveEventPlugin.js#L24-L31
Expand All @@ -92,6 +130,6 @@ fireEvent.select = (node, init) => {

// just re-export everything from dom-testing-library
export * from 'dom-testing-library'
export {render, cleanup, flushEffects}
export {render, testHook, cleanup, fireEvent, act}

/* eslint func-name-matching:0 */
11 changes: 9 additions & 2 deletions typings/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,19 @@ export function render<Q extends Queries>(
options: RenderOptions<Q>,
): RenderResult<Q>

/**
* Renders a test component that calls back to the test.
*/
export function testHook(callback: () => void): void

/**
* Unmounts React trees that were mounted with render.
*/
export function cleanup(): void

/**
* Forces React's `useEffect` hook to run synchronously.
* Simply calls ReactDOMTestUtils.act(cb)
* If that's not available (older version of react) then it
* simply calls the given callback immediately
*/
export function flushEffects(): void
export function act(callback: () => void): void