Skip to content
Open
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
50 changes: 50 additions & 0 deletions src/__tests__/event-wrapper-nesting.js

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Can you write a test showing the underlying issue instead of testing implementation details (nesting depth)?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

sorry about that, I was stumped on it for a little bit
I got there today though, just needed to sleep on it. done.

Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import * as React from 'react'
import {render, fireEvent, getConfig} from '../'

const {useState, useEffect, useRef} = React

const dispatchDOMEvent = (target, type) =>
getConfig().eventWrapper(() =>
target.dispatchEvent(new Event(type, {bubbles: true})),
)

test('does not warn about act when there are nested acts', () => {
function Fixture() {
const [open, setOpen] = useState(false)
const [fromEffect, setFromEffect] = useState(0)
const [fromEvent, setFromEvent] = useState(0)
const targetRef = useRef(null)

useEffect(() => {
// eslint-disable-next-line jest/no-conditional-in-test
if (!open) {
return
}
dispatchDOMEvent(targetRef.current, 'input')
setFromEffect(n => n + 1)
}, [open])

return (
<>
<button onClick={() => setOpen(true)}>
{`open:${open} effect:${fromEffect} event:${fromEvent}`}
</button>
<input ref={targetRef} readOnly onInput={() => setFromEvent(n => n + 1)} />
</>
)
}

const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
const {container} = render(<Fixture />)
const button = container.querySelector('button')

fireEvent.click(button)

expect(button).toHaveTextContent('open:true effect:1 event:1')
const actWarnings = errorSpy.mock.calls
.map(args => String(args[0]))
.filter(message => message.includes('not wrapped in act'))
expect(actWarnings).toEqual([])

errorSpy.mockRestore()
})
20 changes: 15 additions & 5 deletions src/pure.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ function jestFakeTimersAreEnabled() {
return false
}

let inEventWrapper = false

configureDTL({
unstable_advanceTimersWrapper: cb => {
return act(cb)
Expand Down Expand Up @@ -58,11 +60,19 @@ configureDTL({
}
},
eventWrapper: cb => {
let result
act(() => {
result = cb()
})
return result
if (inEventWrapper) {
return cb()
}
inEventWrapper = true
try {
let result
act(() => {
result = cb()
})
return result
} finally {
inEventWrapper = false
}
},
})

Expand Down
Loading