Skip to content

Instantly share code, notes, and snippets.

@sixman9
Created June 11, 2024 11:26
Show Gist options
  • Save sixman9/596ffb556095a9cc2dee3a8db1db9127 to your computer and use it in GitHub Desktop.
Save sixman9/596ffb556095a9cc2dee3a8db1db9127 to your computer and use it in GitHub Desktop.
A bash script to create a JEST-based NodeJS Typescript project for testing out new code fragments
#!/bin/bash
# Function to prompt for a directory name if not provided
prompt_directory_name() {
read -p "Enter the project directory name: " dir_name
if [ -z "$dir_name" ]; then
echo "Directory name cannot be empty. Please try again."
prompt_directory_name
fi
}
# Check if a directory name is passed as an argument
if [ -z "$1" ]; then
prompt_directory_name
dir_name=$dir_name
else
dir_name=$1
fi
# Create the new directory
mkdir -p "$dir_name"
# Navigate into the new directory
cd "$dir_name" || exit
# Initialize a new Node.js project
npm init -y
# Install TypeScript and Jest along with necessary dependencies
npm install --save-dev typescript jest @types/jest ts-jest
# Initialize TypeScript configuration
npx tsc --init
# Write the tsconfig.json file with necessary configurations for ESM
cat <<EOT > tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "node",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.test.ts"]
}
EOT
# Initialize Jest configuration
npx ts-jest config:init
# Ensure the jest.config.js file has necessary settings
cat <<EOT > jest.config.js
export default {
preset: 'ts-jest/presets/default-esm',
testEnvironment: 'node',
testMatch: ['**/?(*.)+(spec|test).[jt]s?(x)'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
extensionsToTreatAsEsm: ['.ts'],
globals: {
'ts-jest': {
useESM: true
}
}
};
EOT
# Create project directory structure
mkdir src
mkdir __tests__
# Create a sample TypeScript file
cat <<EOT > src/mathFunctions.ts
export function add(a: number, b: number): number {
return a + b;
}
export function subtract(a: number, b: number): number {
return a - b;
}
EOT
# Create a sample test file
cat <<EOT > __tests__/mathFunctions.test.ts
import { add, subtract } from '../src/mathFunctions';
test('adds 1 + 2 to equal 3', () => {
expect(add(1, 2)).toBe(3);
});
test('subtracts 5 - 2 to equal 3', () => {
expect(subtract(5, 2)).toBe(3);
});
EOT
# Update package.json for ESM support
jq '.type = "module"' package.json > tmp.$$.json && mv tmp.$$.json package.json
# Add test script to package.json
npm set-script test "jest"
# Notify user of setup completion
echo "Project setup complete in directory $dir_name. You can add your own TypeScript files to the src directory and corresponding tests to the __tests__ directory."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment