bun test や vitest の onTestFinished Hook

note

Bun v1.3.2 で追加され、 Vitest でもサポートされている機能として onFinishedTest という Hook がある。

これは各テストの終了時に実行されるフックで、afterEach よりあとで実行され、テストの成否に関わらず実行されるため、テストで必要だったリソースの解放などに使うことが出来る。

import { afterEach, describe, expect, onTestFinished, test } from 'bun:test';

describe('onTestFinished Hook', () => {
    afterEach(() => {
        console.log('afterEach called');
    });
    test('example', () => {
        onTestFinished(() => {
            console.log('example 1 onTestFinished called');
        });
        expect(1 + 1).toBe(3);
    });
    test('with Error', () => {
        onTestFinished(() => {
            console.log('example 2 onTestFinished called');
        });
        throw new Error();
    });
});

これを実行すると次のようになる:

test/hook.test.ts:
 6 |     });
 7 |     test('example', () => {
 8 |         onTestFinished(() => {
 9 |             console.log('example 1 onTestFinished called');
10 |         });
11 |         expect(1 + 1).toBe(3);
                           ^
error: expect(received).toBe(expected)

Expected: 3
Received: 2

      at <anonymous> (/workspaces/aiblio/test/hook.test.ts:11:23)
afterEach called
example 1 onTestFinished called
✗ onTestFinished Hook > example

12 |     });
13 |     test('with Error', () => {
14 |         onTestFinished(() => {
15 |             console.log('example 2 onTestFinished called');
16 |         });
17 |         throw new Error();
                             ^
Error: 
      at <anonymous> (/workspaces/aiblio/test/hook.test.ts:17:25)
afterEach called
example 2 onTestFinished called
✗ onTestFinished Hook > with Error

 0 pass
 2 fail
 1 expect() calls
Ran 2 tests across 1 file. [62.00ms]
yaakai.to