Skip to content

Commit

Permalink
chore: improve waitFor/waitUntil examples
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va committed Sep 16, 2023
1 parent e0ac97c commit d284e12
Showing 1 changed file with 29 additions and 29 deletions.
58 changes: 29 additions & 29 deletions docs/api/vi.md
Expand Up @@ -730,49 +730,49 @@ This is very useful when you need to wait for some asynchronous action to comple

```ts
import { expect, test, vi } from 'vitest'
import { createServer } from './server.js'

test('Server started successfully', async () => {
let server = false
const server = createServer()

setTimeout(() => {
server = true
}, 100)

function checkServerStart() {
if (!server)
throw new Error('Server not started')

console.log('Server started')
}
await vi.waitFor(
() => {
if (!server.isReady)
throw new Error('Server not started')

const res = await vi.waitFor(checkServerStart, {
timeout: 500, // default is 1000
interval: 20, // default is 50
})
expect(server).toBe(true)
console.log('Server started')
}, {
timeout: 500, // default is 1000
interval: 20, // default is 50
}
)
expect(server.isReady).toBe(true)
})
```

It also works for asynchronous callbacks

```ts
import { expect, test, vi } from 'vitest'
// @vitest-environment jsdom

test('Server started successfully', async () => {
async function startServer() {
return new Promise((resolve) => {
setTimeout(() => {
server = true
resolve('Server started')
}, 100)
})
}

const server = await vi.waitFor(startServer, {
import { expect, test, vi } from 'vitest'
import { getDOMElementAsync, populateDOMAsync } from './dom.js'

test('Element exists in a DOM', async () => {
// start populating DOM
populateDOMAsync()

const element = await vi.waitFor(async () => {
// try to get the element until it exists
const element = await getDOMElementAsync() as HTMLElement | null
expect(element).toBeTruthy()
expect(element.dataset.initialized).toBeTruthy()
return element
}, {
timeout: 500, // default is 1000
interval: 20, // default is 50
})
expect(server).toBe('Server started')
expect(element).toBeInstanceOf(HTMLElement)
})
```

Expand Down

0 comments on commit d284e12

Please sign in to comment.