Skip to content
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
9 changes: 9 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {getQueriesForElement, prettyDOM} from '@testing-library/dom'
import {tick} from 'svelte'

export * from '@testing-library/dom'
const mountedContainers = new Set()
Expand Down Expand Up @@ -36,3 +37,11 @@ const cleanupAtContainer = container => {
export const cleanup = () => {
mountedContainers.forEach(cleanupAtContainer)
}

export function act(fn) {
const returnValue = fn()
if (returnValue !== undefined && typeof returnValue.then === 'function') {
return returnValue.then(() => tick())
}
return tick()
}
35 changes: 35 additions & 0 deletions tests/act.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import {act, render, fireEvent, cleanup} from '../src'
import App from './example/App.svelte'
import 'jest-dom/extend-expect'

afterEach(cleanup)

test('after awaited state updates are flushed', async () => {
const {getByText} = render(App, {props: {name: 'world'}})
const button = getByText('Button Text')

const acting = act(() => {
fireEvent.click(button)
})
expect(button).toHaveTextContent('Button Text')

await acting
expect(button).toHaveTextContent('Button Clicked')
})

test('accepts async functions', async () => {
function sleep(ms) {
return new Promise(resolve => {
setTimeout(() => resolve(), ms)
})
}

const {getByText} = render(App, {props: {name: 'world'}})
const button = getByText('Button Text')

await act(async () => {
await sleep(100)
fireEvent.click(button)
})
expect(button).toHaveTextContent('Button Clicked')
})