VitestのIn-source testingを使ってみたのでメモ📝
In-source testing
とは?
以下のようにコード上のimport.meta.vitest
の中にテストコードを直接書くことができる機能
// src/index.ts // the implementation export function add(...args: number[]) { return args.reduce((a, b) => a + b, 0) } // in-source test suites if (import.meta.vitest) { const { it, expect } = import.meta.vitest it('add', () => { expect(add()).toBe(0) expect(add(1)).toBe(1) expect(add(1, 2, 3)).toBe(6) }) }
導入方法
vite.config.ts
内のdefineにbuild時にテストコードが含まれないように'import.meta.vitest': 'undefined',
を追加するのと、
includeSource
にIn-source testingを使いたいディレクトリパスを追加する。
// vite.config.ts import { defineConfig } from 'vitest/config' export default defineConfig({ + define: { + 'import.meta.vitest': 'undefined', + }, test: { + includeSource: ['src/**/*.{js,ts}'] }, })
includeSource
に追加することでimport.meta.vitest
があるファイルだけがテスト対象となる。
includeSource
- Type: string
- Default:
Include globs for in-source test files. When defined, Vitest will run all matched files with import.meta.vitest inside.
またTypeScriptを使用している場合にはtsconfig.json
のtype
に"vitest/importMeta"
を追加する。
{
"compilerOptions": {
"types": [
+ "vitest/importMeta"
テストコードの書き方
以下のようにimport.meta.vitest
の中にテストコードを直接書ける。
export function truncate(value: string, limit: number): string { if (value.length <= limit) return value; return `${value.trim().replace(/\s+/g, "").substring(0, limit)}…`; } if (import.meta.vitest) { const { describe, it, expect } = import.meta.vitest; describe("truncate", () => { it("文字列が指定した文字数で切り詰められること", () => { expect(truncate("あいうえお", 3)).toEqual("あいう…"); }); }); }