アプリ svelte-vite-jest の初期化
npm init vite@latest svelte-vite-jest -- --template svelte-ts
cd
npm install
サンプルとしてクリックすると数値が1ずつ増えていくボタンが設置されています。
src/App.svelte の余計なコードを削除して以下のようにしておきます
<script lang="ts">
import Counter from './lib/Counter.svelte'
</script>
<main>
<div class="card">
<Counter />
</div>
</main>
Counter.svelte は次のように修正しておきます
<script lang="ts">
let count: number = 1
const increment = () => {
count += 1
}
</script>
<button on:click={increment}>
count is {count}
</button>
npm install -D vitest
npm install -D @testing-library/svelte
npm install -D happy-dom
vite.config.ts
/// <reference types="vitest" />
import { defineConfig } from 'vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [svelte()],
test: {
environment: 'happy-dom',
},
});
ディレクトリ tests にテストファイルを作成する
src/tests/app.svelte.test.ts
import { describe, expect, test } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/svelte';
import App from '../../src/App.svelte';
describe('App.svelte', () => {
render(App);
test('1+2は3になる ', () => {
expect(1 + 2).toEqual(3);
});
test('アプリをマウントすると count is 1 が表示される', () => {
expect(screen.getByRole('button').innerHTML).toEqual('count is 1');
});
test('ボタンをクリックするとカウントの数値が2になる', async () => {
const button = screen.getByRole('button');
await fireEvent.click(button);
console.log(button.innerHTML);
expect(screen.getByRole('button').innerHTML).toEqual('count is 2');
});
});
npx vitest --reporter verbose