You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: docs/api/index.md
+97
Original file line number
Diff line number
Diff line change
@@ -853,6 +853,10 @@ afterEach(async () => {
853
853
854
854
Here, the `afterEach` ensures that testing data is cleared after each test runs.
855
855
856
+
::: tip
857
+
Vitest 1.3.0 added [`onTestFinished`](##ontestfinished-1-3-0) hook. You can call it during the test execution to cleanup any state after the test has finished running.
This hook is always called after the test has finished running. It is called after `afterEach` hooks since they can influence the test result. It receives a `TaskResult` object with the current test result.
925
+
926
+
```ts
927
+
import { onTestFinished, test } from'vitest'
928
+
929
+
test('performs a query', () => {
930
+
const db =connectDb()
931
+
onTestFinished(() =>db.close())
932
+
db.query('SELECT * FROM users')
933
+
})
934
+
```
935
+
936
+
::: warning
937
+
If you are running tests concurrently, you should always use `onTestFinished` hook from the test context since Vitest doesn't track concurrent tests in global hooks:
938
+
939
+
```ts
940
+
import { test } from'vitest'
941
+
942
+
test.concurrent('performs a query', (t) => {
943
+
const db =connectDb()
944
+
t.onTestFinished(() =>db.close())
945
+
db.query('SELECT * FROM users')
946
+
})
947
+
```
948
+
:::
949
+
950
+
This hook is particularly useful when creating reusable logic:
951
+
952
+
```ts
953
+
// this can be in a separate file
954
+
function getTestDb() {
955
+
const db =connectMockedDb()
956
+
onTestFinished(() =>db.close())
957
+
returndb
958
+
}
959
+
960
+
test('performs a user query', async () => {
961
+
const db =getTestDb()
962
+
expect(
963
+
awaitdb.query('SELECT * from users').perform()
964
+
).toEqual([])
965
+
})
966
+
967
+
test('performs an organization query', async () => {
968
+
const db =getTestDb()
969
+
expect(
970
+
awaitdb.query('SELECT * from organizations').perform()
971
+
).toEqual([])
972
+
})
973
+
```
974
+
975
+
### onTestFailed
976
+
977
+
This hook is called only after the test has failed. It is called after `afterEach` hooks since they can influence the test result. It receives a `TaskResult` object with the current test result. This hook is useful for debugging.
978
+
979
+
```ts
980
+
import { onTestFailed, test } from'vitest'
981
+
982
+
test('performs a query', () => {
983
+
const db =connectDb()
984
+
onTestFailed((e) => {
985
+
console.log(e.result.errors)
986
+
})
987
+
db.query('SELECT * FROM users')
988
+
})
989
+
```
990
+
991
+
::: warning
992
+
If you are running tests concurrently, you should always use `onTestFailed` hook from the test context since Vitest doesn't track concurrent tests in global hooks:
0 commit comments