Skip to content

Instantly share code, notes, and snippets.

@jonfazzaro
Last active March 14, 2025 20:05
Show Gist options
  • Save jonfazzaro/05d6f43c98100838ac528b4edb2daec6 to your computer and use it in GitHub Desktop.
Save jonfazzaro/05d6f43c98100838ac528b4edb2daec6 to your computer and use it in GitHub Desktop.
An init script for vitest/react/TypeScript
#! /bin/bash
function main() {
install_packages
add_setup
add_configuration
configure_compilation
add_test_script
}
function install_packages() {
npm install --save-dev \
vitest \
@vitest/expect \
@testing-library/react \
@testing-library/jest-dom \
jsdom
}
function edit_file() {
echo "$2" > tmp
mv tmp "$1"
}
function strip_comments_from() {
edit_file "$1" "$(yes | npx strip-json-comments-cli "$1")"
}
function edit_json() {
strip_comments_from "$1"
edit_file "$1" "$(yes | npx node-jq "$2" "$1")"
}
function configure_compilation() {
edit_json tsconfig.app.json '.compilerOptions.types += ["vitest/globals", "@testing-library/jest-dom"]'
}
function add_test_script() {
edit_json package.json '.scripts.test = "vitest"'
}
function add_setup() {
cat <<EOF > ./src/vitest.setup.ts
import { expect, afterEach } from 'vitest';
import { cleanup } from '@testing-library/react';
import * as matchers from '@testing-library/jest-dom/matchers';
expect.extend(matchers);
afterEach(() => {
cleanup();
});
EOF
}
function add_configuration() {
cat <<EOF > ./vitest.config.ts
import { defineConfig, UserConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
test: {
globals: true,
environment: 'jsdom',
setupFiles: './src/vitest.setup.ts',
},
} as UserConfig);
EOF
}
main
@jonfazzaro
Copy link
Author

jonfazzaro commented Mar 5, 2025

Run this in your project directory after scaffolding vite/react-ts.

Example usage:

npm create -y vite@latest my-react-app -- --template react-ts
cd my-react-app
vitest-init

Hat-tip: this is a script version of @john-smilga's walk-through.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment