vitest テストの前処理、後処理 - kocya-dev/note GitHub Wiki

vitest.setup.ts (vitest.configでsetupFilesに指定したsetupファイル)

beforeAll(() => { console.log("setup.beforeAll"); });
afterAll(() => { console.log("setup.afterAll"); });
beforeEach(() => { console.log("setup.beforeEach"); });
afterEach(() => { console.log("setup.afterEach"); });

example.test.ts

describe("parent", () => {
  beforeAll(() => { console.log("parent.beforeAll"); });
  afterAll(() => { console.log("parent.afterAll"); });
  beforeEach(() => { console.log("parent.beforeEach"); });
  afterEach(() => { console.log("parent.afterEach"); });
  describe("child", () => {
    beforeAll(() => { console.log("child.beforeAll"); });
    afterAll(() => { console.log("child.afterAll"); });
    beforeEach(() => { console.log("child.beforeEach"); });
    afterEach(() => { console.log("child.afterEach"); });
    it("test", async () => { console.log("test"); });
  });
});

実行結果

stdout | vitest.setup.ts:2:11
setup.beforeAll

stdout | test\example.test.ts:3:13
parent.beforeAll

stdout | test\example.test.ts:16:15
child.beforeAll

stdout | test/example.test.ts > parent > child > test
setup.beforeEach
parent.beforeEach
child.beforeEach
test
child.afterEach
parent.afterEach
setup.afterEach

stdout | test\example.test.ts:19:15
child.afterAll

stdout | test\example.test.ts:6:13
parent.afterAll

stdout | vitest.setup.ts:5:11
setup.afterAll