Config option for setting pretendToBeVisual
See original GitHub issue🚀 Feature Proposal
An option to set jsdom pretendToBeVisual
inside test cases.
Motivation
I need to test code that set a timestamp value depending on document.hidden
.
jsdom toggles the value depending on pretendToBeVisual
as documented in the jsdom README.
Currently pretendToBeVisual
appears to be set on test start and not changeable from within a single test.
I see that I can set a custom environment configuration documentation.
Example
To test the following function getTimeDuration
:
/**
* First call starts a timer and returns a function
* that when called will give the elapsed time in
* milisecond, while subtracting "hidden" time.
* @returns {function} Calling this function will return the elapsed time.
*/
export default function getTimeDuration () {
const startTimestamp = Date.now()
let hiddenTimeDelta = 0
let hiddenTimeStart = 0
document.addEventListener('visibilitychange', trackHiddenTime)
function trackHiddenTime () {
if (document.hidden) {
hiddenTimeStart = Date.now()
} else {
hiddenTimeDelta += (Date.now() - hiddenTimeStart)
}
}
return () => {
document.removeEventListener('visibilitychange', trackHiddenTime)
return (Date.now() - hiddenTimeDelta) - startTimestamp
}
}
We could write the following test code:
test('visibilitychange duration used by PayloadTiming', () => {
// jestDateMock.advanceTo(0) is
// needed due to issue: https://github.com/hustcc/jest-date-mock/issues/15
jestDateMock.advanceTo(0)
const timer = getTimeDuration()
jestDateMock.advanceBy(10) // visible state
jsdom.pretendToBeVisual = false // hidden state
document.dispatchEvent(new Event('visibilitychange'))
jestDateMock.advanceBy(10)
jsdom.pretendToBeVisual = true // visible state
document.dispatchEvent(new Event('visibilitychange'))
jestDateMock.advanceBy(10)
expect(timer()).toBe(20)
jestDateMock.clear()
})
Pitch
Currently, I do not see any way to test the Page Visibility API in jest without this option. Regardless of the actual name. I’m not attached in any way to jsdom.pretendToBeVisual
.
Please let me know if this change has to be done upstream in jsdom before it can be available in jest or if there is work-around possible in how jest utilitizes jsdom.
Issue Analytics
- State:
- Created 5 years ago
- Comments:7
Top GitHub Comments
For future readers who find this thread.
The simple and correct way to set
document.hidden
in jest and jsdom is to add the following to your test.In effect you will shadow
document.hidden
. A declined patch that also setsvisibilityState
can be found here: https://github.com/jsdom/jsdom/pull/2392This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.