From 385a28ed029d12b27d5fc0c8f6e9ffdef02dad56 Mon Sep 17 00:00:00 2001 From: Sebastian Silbermann Date: Tue, 30 Jul 2019 09:04:23 +0000 Subject: [PATCH 1/2] feat: Add act --- src/index.js | 9 +++++++++ tests/act.spec.js | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 tests/act.spec.js diff --git a/src/index.js b/src/index.js index 9cd3ce9..6d89398 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 != null && 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') +}) From 50fcae7c7a8aff201e865131c9742fec9be10c68 Mon Sep 17 00:00:00 2001 From: Sebastian Silbermann Date: Mon, 5 Aug 2019 19:57:48 +0200 Subject: [PATCH 2/2] Expect nothing to be returned or thenable --- src/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/index.js b/src/index.js index 6d89398..6ef0282 100644 --- a/src/index.js +++ b/src/index.js @@ -40,7 +40,7 @@ export const cleanup = () => { export function act(fn) { const returnValue = fn() - if (returnValue != null && typeof returnValue.then === 'function') { + if (returnValue !== undefined && typeof returnValue.then === 'function') { return returnValue.then(() => tick()) } return tick()