diff --git a/src/index.js b/src/index.js index 9cd3ce9..6ef0282 100644 --- a/src/index.js +++ b/src/index.js @@ -1,4 +1,5 @@ import {getQueriesForElement, prettyDOM} from '@testing-library/dom' +import {tick} from 'svelte' export * from '@testing-library/dom' const mountedContainers = new Set() @@ -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() +} diff --git a/tests/act.spec.js b/tests/act.spec.js new file mode 100644 index 0000000..96931a1 --- /dev/null +++ b/tests/act.spec.js @@ -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') +})