Skip to content

Upgrade wait-for-expect package #342

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 14 commits into from
Sep 5, 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
62 changes: 61 additions & 1 deletion src/__tests__/wait-for-dom-change.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
import {waitForDomChange} from '../wait-for-dom-change'
import {renderIntoDocument} from './helpers/test-utils'

function importModule() {
return require('../').waitForDomChange
}

let waitForDomChange

beforeEach(() => {
jest.useRealTimers()
jest.resetModules()
waitForDomChange = importModule()
})

test('waits for the dom to change in the document', async () => {
const {container} = renderIntoDocument('<div />')
const promise = waitForDomChange()
Expand Down Expand Up @@ -48,3 +59,52 @@ Array [
]
`)
})

describe('timers', () => {
const expectElementToChange = async () => {
const importedWaitForDomChange = importModule()
const {container} = renderIntoDocument('<div />')

setTimeout(() => container.firstChild.setAttribute('id', 'foo'), 100)

const promise = importedWaitForDomChange({container, timeout: 200})

if (setTimeout._isMockFunction) {
jest.advanceTimersByTime(110)
}

await expect(promise).resolves.toMatchInlineSnapshot(`
Array [
Object {
"addedNodes": Array [],
"attributeName": "id",
"attributeNamespace": null,
"nextSibling": null,
"oldValue": null,
"previousSibling": null,
"removedNodes": Array [],
"target": <div
id="foo"
/>,
"type": "attributes",
},
]
`)
}

it('works with real timers', async () => {
jest.useRealTimers()
await expectElementToChange()
})
it('works with fake timers', async () => {
jest.useFakeTimers()
await expectElementToChange()
})
})

test("doesn't change jest's timers value when importing the module", () => {
jest.useFakeTimers()
importModule()

expect(window.setTimeout._isMockFunction).toEqual(true)
})
62 changes: 61 additions & 1 deletion src/__tests__/wait-for-element-to-be-removed.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
import {waitForElementToBeRemoved} from '../'
import {renderIntoDocument} from './helpers/test-utils'

function importModule() {
return require('../').waitForElementToBeRemoved
}

let waitForElementToBeRemoved

beforeEach(() => {
jest.useRealTimers()
jest.resetModules()
waitForElementToBeRemoved = importModule()
})

test('resolves on mutation only when the element is removed', async () => {
const {queryAllByTestId} = renderIntoDocument(`
<div data-testid="div"></div>
Expand Down Expand Up @@ -57,3 +68,52 @@ test('requires an unempty array of elements to exist first', () => {
`"The callback function which was passed did not return an element or non-empty array of elements. waitForElementToBeRemoved requires that the element(s) exist before waiting for removal."`,
)
})

describe('timers', () => {
const expectElementToBeRemoved = async () => {
const importedWaitForElementToBeRemoved = importModule()

const {queryAllByTestId} = renderIntoDocument(`
<div data-testid="div"></div>
<div data-testid="div"></div>
`)
const divs = queryAllByTestId('div')
// first mutation
setTimeout(() => {
divs.forEach(d => d.setAttribute('id', 'mutated'))
})
// removal
setTimeout(() => {
divs.forEach(div => div.parentElement.removeChild(div))
}, 100)

const promise = importedWaitForElementToBeRemoved(
() => queryAllByTestId('div'),
{
timeout: 200,
},
)

if (setTimeout._isMockFunction) {
jest.advanceTimersByTime(110)
}

await promise
}

it('works with real timers', async () => {
jest.useRealTimers()
await expectElementToBeRemoved()
})
it('works with fake timers', async () => {
jest.useFakeTimers()
await expectElementToBeRemoved()
})
})

test("doesn't change jest's timers value when importing the module", () => {
jest.useFakeTimers()
importModule()

expect(window.setTimeout._isMockFunction).toEqual(true)
})
44 changes: 43 additions & 1 deletion src/__tests__/wait-for-element.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
import {waitForElement} from '../wait-for-element'
import {render, renderIntoDocument} from './helpers/test-utils'

function importModule() {
return require('../').waitForElement
}

let waitForElement

beforeEach(() => {
jest.useRealTimers()
jest.resetModules()
waitForElement = importModule()
})

test('waits for element to appear in the document', async () => {
const {rerender, getByTestId} = renderIntoDocument('<div />')
const promise = waitForElement(() => getByTestId('div'))
Expand Down Expand Up @@ -48,3 +59,34 @@ test('waits until callback does not return null', async () => {
test('throws error if no callback is provided', async () => {
await expect(waitForElement()).rejects.toThrow(/callback/i)
})

describe('timers', () => {
const expectElementToExist = async () => {
const importedWaitForElement = importModule()

const {rerender, getByTestId} = renderIntoDocument('<div />')

setTimeout(() => rerender('<div data-testid="div" />'), 100)

const promise = importedWaitForElement(() => getByTestId('div'), {
timeout: 200,
})

if (setTimeout._isMockFunction) {
jest.advanceTimersByTime(110)
}

const element = await promise

await expect(element).toBeInTheDocument()
}

it('works with real timers', async () => {
jest.useRealTimers()
await expectElementToExist()
})
it('works with fake timers', async () => {
jest.useFakeTimers()
await expectElementToExist()
})
})
35 changes: 31 additions & 4 deletions src/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,42 @@ import MutationObserver from '@sheerun/mutationobserver-shim'

const globalObj = typeof window === 'undefined' ? global : window

// Currently this fn only supports jest timers, but it could support other test runners in the future.
function runWithRealTimers(callback) {
const usingJestFakeTimers =
globalObj.setTimeout._isMockFunction && typeof jest !== 'undefined'

if (usingJestFakeTimers) {
jest.useRealTimers()
}

const callbackReturnValue = callback()

if (usingJestFakeTimers) {
jest.useFakeTimers()
}

return callbackReturnValue
}

// we only run our tests in node, and setImmediate is supported in node.
// istanbul ignore next
function setImmediatePolyfill(fn) {
return globalObj.setTimeout(fn, 0)
}

const clearTimeoutFn = globalObj.clearTimeout
// istanbul ignore next
const setImmediateFn = globalObj.setImmediate || setImmediatePolyfill
const setTimeoutFn = globalObj.setTimeout
function getTimeFunctions() {
// istanbul ignore next
return {
clearTimeoutFn: globalObj.clearTimeout,
setImmediateFn: globalObj.setImmediate || setImmediatePolyfill,
setTimeoutFn: globalObj.setTimeout,
}
}

const {clearTimeoutFn, setImmediateFn, setTimeoutFn} = runWithRealTimers(
getTimeFunctions,
)

function newMutationObserver(onMutation) {
const MutationObserverConstructor =
Expand All @@ -37,4 +63,5 @@ export {
clearTimeoutFn as clearTimeout,
setImmediateFn as setImmediate,
setTimeoutFn as setTimeout,
runWithRealTimers,
}
5 changes: 4 additions & 1 deletion src/wait-for-dom-change.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
setImmediate,
setTimeout,
clearTimeout,
runWithRealTimers,
} from './helpers'
import {getConfig} from './config'

Expand All @@ -20,7 +21,9 @@ function waitForDomChange({
return new Promise((resolve, reject) => {
const timer = setTimeout(onTimeout, timeout)
const observer = newMutationObserver(onMutation)
observer.observe(container, mutationObserverOptions)
runWithRealTimers(() =>
observer.observe(container, mutationObserverOptions),
)

function onDone(error, result) {
clearTimeout(timer)
Expand Down
5 changes: 4 additions & 1 deletion src/wait-for-element-to-be-removed.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
setImmediate,
setTimeout,
clearTimeout,
runWithRealTimers,
} from './helpers'
import {getConfig} from './config'

Expand Down Expand Up @@ -43,7 +44,9 @@ function waitForElementToBeRemoved(
)
} else {
// Only observe for mutations only if there is element while checking synchronously
observer.observe(container, mutationObserverOptions)
runWithRealTimers(() =>
observer.observe(container, mutationObserverOptions),
)
}
} catch (error) {
onDone(error)
Expand Down
5 changes: 4 additions & 1 deletion src/wait-for-element.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
setImmediate,
setTimeout,
clearTimeout,
runWithRealTimers,
} from './helpers'
import {getConfig} from './config'

Expand Down Expand Up @@ -31,7 +32,9 @@ function waitForElement(
const timer = setTimeout(onTimeout, timeout)

const observer = newMutationObserver(onMutation)
observer.observe(container, mutationObserverOptions)
runWithRealTimers(() =>
observer.observe(container, mutationObserverOptions),
)
function onDone(error, result) {
clearTimeout(timer)
setImmediate(() => observer.disconnect())
Expand Down