Skip to content

Commit d26a497

Browse files
eps1lonbenmonro
authored andcommitted
feat: Add act (#41)
* feat: Add act * Expect nothing to be returned or thenable
1 parent 4c3876e commit d26a497

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/index.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {getQueriesForElement, prettyDOM} from '@testing-library/dom'
2+
import {tick} from 'svelte'
23

34
export * from '@testing-library/dom'
45
const mountedContainers = new Set()
@@ -36,3 +37,11 @@ const cleanupAtContainer = container => {
3637
export const cleanup = () => {
3738
mountedContainers.forEach(cleanupAtContainer)
3839
}
40+
41+
export function act(fn) {
42+
const returnValue = fn()
43+
if (returnValue !== undefined && typeof returnValue.then === 'function') {
44+
return returnValue.then(() => tick())
45+
}
46+
return tick()
47+
}

tests/act.spec.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import {act, render, fireEvent, cleanup} from '../src'
2+
import App from './example/App.svelte'
3+
import 'jest-dom/extend-expect'
4+
5+
afterEach(cleanup)
6+
7+
test('after awaited state updates are flushed', async () => {
8+
const {getByText} = render(App, {props: {name: 'world'}})
9+
const button = getByText('Button Text')
10+
11+
const acting = act(() => {
12+
fireEvent.click(button)
13+
})
14+
expect(button).toHaveTextContent('Button Text')
15+
16+
await acting
17+
expect(button).toHaveTextContent('Button Clicked')
18+
})
19+
20+
test('accepts async functions', async () => {
21+
function sleep(ms) {
22+
return new Promise(resolve => {
23+
setTimeout(() => resolve(), ms)
24+
})
25+
}
26+
27+
const {getByText} = render(App, {props: {name: 'world'}})
28+
const button = getByText('Button Text')
29+
30+
await act(async () => {
31+
await sleep(100)
32+
fireEvent.click(button)
33+
})
34+
expect(button).toHaveTextContent('Button Clicked')
35+
})

0 commit comments

Comments
 (0)