Last active
March 14, 2025 20:05
-
-
Save jonfazzaro/05d6f43c98100838ac528b4edb2daec6 to your computer and use it in GitHub Desktop.
An init script for vitest/react/TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run this in your project directory after scaffolding vite/react-ts.
Example usage:
Hat-tip: this is a script version of @john-smilga's walk-through.