Skip to content

Commit

Permalink
fix(runner): fix async fixture teardown (#4700)
Browse files Browse the repository at this point in the history
  • Loading branch information
hi-ogawa committed Dec 9, 2023
1 parent 37388d6 commit 92afd54
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
13 changes: 9 additions & 4 deletions packages/runner/src/fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,17 @@ export function withFixtures(fn: Function, testContext?: TestContext) {
if (fixture.isFn) {
// wait for `use` call to extract fixture value
const useFnArgPromise = createDefer()
fixture.value(context, async (useFnArg: unknown) => {
const fixtureReturn = fixture.value(context, async (useFnArg: unknown) => {
useFnArgPromise.resolve(useFnArg)
// suspend fixture teardown until cleanup
const teardownPromise = createDefer<void>()
cleanupFnArray.push(teardownPromise.resolve)
await teardownPromise
const useReturnPromise = createDefer<void>()
cleanupFnArray.push(async () => {
// start teardown by resolving `use` Promise
useReturnPromise.resolve()
// wait for finishing teardown
await fixtureReturn
})
await useReturnPromise
}).catch(useFnArgPromise.reject) // treat fixture function error (until `use` call) as test failure
resolvedValue = await useFnArgPromise
}
Expand Down
30 changes: 30 additions & 0 deletions test/core/test/test-extend.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -354,3 +354,33 @@ test('teardown should be called once time', () => {
expect(numbers).toHaveLength(0)
expect(teardownFn).toBeCalledTimes(1)
})

describe('asynchonous setup/teardown', () => {
const trackFn = vi.fn()

const myTest = test.extend<{ a: string }>({
a: async ({}, use) => {
trackFn('setup-sync')
await new Promise(resolve => setTimeout(resolve, 200))
trackFn('setup-async')
await use('ok')
trackFn('teardown-sync')
await new Promise(resolve => setTimeout(resolve, 200))
trackFn('teardown-async')
},
})

myTest('quick test', ({ a }) => {
expect(a).toBe('ok')
expect(trackFn.mock.calls).toEqual([['setup-sync'], ['setup-async']])
})

afterAll(() => {
expect(trackFn.mock.calls).toEqual([
['setup-sync'],
['setup-async'],
['teardown-sync'],
['teardown-async'],
])
})
})

0 comments on commit 92afd54

Please sign in to comment.