Skip to content

feat: Add act #41

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 2 commits into from
Aug 11, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
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 != null && 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')
})