test-weaver
v1.7.0
Published
CLI tool that weaves Jest-compatible .test.js files from simple YAML definitions.
Maintainers
Readme
Test Weaver
A command-line utility that skillfully weaves Jest-compatible test files from simple, declarative YAML threads.
This project provides a solid foundation for building high-quality JavaScript applications, ensuring code consistency and best practices from the start.
📚 Table of Contents
- ✨ Key Features
- How It Works: From YAML to Jest
- 🚀 Getting Started
- Usage
- ⚙️ Configuration
- API
- 🚀 Available Scripts
- A Focus on Quality and Productivity
- 📦 Release & Versioning
- 📁 Project Structure
- ✍️ Linting for Documentation
- 🐞 Bug Reports
- 🤝 Contributing
- 🗺️ Roadmap
- ⚖️ Code of Conduct
- 🙏 Acknowledgements
- 👨💻 About the Author
- 📄 License
✨ Key Features
- Declarative Test Generation: Define your Jest tests in simple, human-readable YAML files. No more boilerplate.
- YAML to Jest: Automatically converts your YAML test definitions into fully functional
*.test.jsfiles, ready to be run by Jest. - Watch Mode: Automatically re-generate test files whenever your YAML definitions change.
- Customizable Configuration: Use a
testweaver.jsonfile to configure input/output directories and other options. See the default configuration for all available settings. - Configuration Schema: Auto-generate a JSON schema for your configuration file to enable validation and autocompletion in your editor.
- Security: Prevents writing generated files to unsafe locations outside the project directory, enhancing project integrity.
How It Works: From YAML to Jest
test-weaver simplifies test creation by transforming a clear, human-readable YAML file into a standard Jest test file. It interprets nested structures as test suites (describe) and leaf items as individual tests (it), with bullet points serving as assertions.
Example YAML Input
This YAML file, cli-tests.test.yaml, demonstrates how test-weaver interprets a free-form, nested YAML structure to generate Jest tests.
'Given a CLI':
'When invoked without arguments':
- 'It should display the help screen'
- 'process should exit with code 0'
'When invoked with --version':
- 'It should display the current version'
- 'process should exit with code 0'
'Given a command "generate"':
'When invoked with valid patterns':
- 'It should create test files'
- 'It should log success messages'
'When invoked with invalid patterns':
- 'It should log an error'
- 'process should exit with code 1'Generated .test.js Output
After running test-weaver, the following cli-tests.test.js file is generated, perfectly mirroring the structure of the YAML input, with unit tests marked as it.todo.
describe('Given a CLI', () => {
describe('When invoked without arguments', () => {
it.todo('It should display the help screen');
it.todo('process should exit with code 0');
});
describe('When invoked with --version', () => {
it.todo('It should display the current version');
it.todo('process should exit with code 0');
});
describe('Given a command "generate"', () => {
describe('When invoked with valid patterns', () => {
it.todo('It should create test files');
it.todo('It should log success messages');
});
describe('When invoked with invalid patterns', () => {
it.todo('It should log an error');
it.todo('process should exit with code 1');
});
});
});Jest Output
When Jest executes the generated .test.js file, it will report the it.todo tests as follows:
PASS ./cli-tests.test.js
Given a CLI
When invoked without arguments
✓ It should display the help screen (todo)
✓ process should exit with code 0 (todo)
When invoked with --version
✓ It should display the current version (todo)
✓ process should exit with code 0 (todo)
Given a command "generate"
When invoked with valid patterns
✓ It should create test files (todo)
✓ It should log success messages (todo)
When invoked with invalid patterns
✓ It should log an error (todo)
✓ process should exit with code 1 (todo)
Test Suites: 1 passed, 1 total
Tests: 8 todo, 8 total
Snapshots: 0 total
Time: 0.XXX s
Ran all test suites.This example illustrates how test-weaver bridges the gap between simple, declarative definitions and executable test code, maintaining a clean and organized testing structure.
🚀 Getting Started
Prerequisites
- Node.js version 18.0.0 or higher
Installation
Install via npm (recommended)
npm install -g test-weaver
# testweaver is now available globally.
# check it's available by running:
# testweaver -VOr use npx (no global install required)
npx test-weaver input.yaml output.test
# npx test-weaver --help
# npx test-weaver --version
# npx test-weaver generate input.yaml output.test
# npx test-weaver init -h
# npx test-weaver init -q -f --no-defaultsOr clone and run locally
git clone https://github.com/ioncakephper/test-weaver.git
cd test-weaver
npm install
npm linkUsage
testweaver is a command-line utility that can be invoked using testweaver (if installed globally via npm install -g test-weaver) or npx test-weaver (for one-off use without global installation).
# Display help information for the main command
testweaver --help
testweaver -h
# Display version information for the main command
testweaver --version
testweaver -VDefault Command: generate
When no specific command is provided, test-weaver defaults to the generate command. This means you can omit generate from your command line.
# Generates test files based on configuration or default patterns
testweaver
# Same as above, explicitly calling the generate command
testweaver generate
# Using the alias for generate
testweaver g
# Display help information for the generate command
testweaver generate --help
testweaver generate -h
testweaver g --help
testweaver g -h
# Generate with specific patterns (long form)
testweaver generate "src/**/*.yaml" "features/**/*.yml"
# Generate with specific patterns (short form)
testweaver g "src/**/*.yaml"
# Generate with a custom config file
testweaver generate --config my-custom-config.json
testweaver g -c my-custom-config.json
# Generate and watch for changes
testweaver generate --watch
testweaver g -w
# Generate with patterns and watch for changes
testweaver generate "src/**/*.yaml" --watch
testweaver g "src/**/*.yaml" -w
# Perform a dry run (simulate generation without writing files)
testweaver generate --dry-run
testweaver g -n
# Specify a different test keyword (e.g., 'test' instead of 'it')
testweaver generate --test-keyword test
testweaver g -k test
# Generate with a custom output directory, preserving the source folder structure
# For a source file at 'tests/sample/cli.test.yaml', the output will be 'out/tests/sample/cli.test.js'
testweaver generate --output-dir out
testweaver g -o out
# Disable cleanup of generated files when source YAML is unlinked in watch mode
testweaver generate --no-cleanupinit Command
Initializes a new project by creating a testweaver.json configuration file.
# Create a default testweaver.json in the current directory (interactive mode)
testweaver init
testweaver i
# Display help information for the init command
testweaver init --help
testweaver init -h
testweaver i --help
testweaver i -h
# Create a default testweaver.json without interactive prompts
testweaver init --quick
testweaver i -q
# Create a custom config file named 'my-config.json'
testweaver init my-config.json
testweaver i my-config.json
# Force overwrite an existing config file
testweaver init --force
testweaver i -f
# Create a config file with only non-default settings
testweaver init --no-defaults
testweaver i --no-defaults
# Combine options: quick, force, and custom filename
testweaver init my-config.json --quick --force
testweaver i my-config.json -q -f⚙️ Configuration
test-weaver is designed to work out-of-the-box with zero configuration, but you can customize its behavior by creating a testweaver.json file in your project root. When you run the init command, a configuration file is created with the default settings.
The default settings are defined in config/default.json. Let's break down what they mean:
patterns
This is an array of glob patterns that test-weaver uses to find your YAML test definition files. By default, it looks for files that:
- Are in any
__tests__directory and end with.yamlor.yml.- Example Match:
src/components/__tests__/button.yaml
- Example Match:
- End with
.test.yamlor.test.yml.- Example Match:
src/utils/parser.test.yml
- Example Match:
- End with
.spec.yamlor.spec.yml.- Example Match:
src/api/user.spec.yaml
- Example Match:
- Are inside a top-level
testsdirectory and end with.yamlor.yml.- Example Match:
tests/integration/auth.yml
- Example Match:
- Are inside a top-level
featuresdirectory and end with.yamlor.yml.- Example Match:
features/login.yaml
- Example Match:
You can override these patterns in your own testweaver.json or by providing them directly on the command line.
ignore
This array tells test-weaver which files or directories to exclude, even if they match the patterns above. The default ignore patterns are:
node_modules: To avoid scanning dependency folders..git: To avoid scanning Git-related folders.temp_files/**/*.{yaml,yml}: A sample pattern to exclude temporary test files.
Other Settings
testKeyword: Specifies the Jest test function to use. Allowed values are"it"(default) and"test".verbose,debug,silent: Control the logging level. These are typically set via command-line flags (--verbose,--debug,--silent).dryRun: Iftrue, simulates test generation without writing any files. Set via--dry-run.noCleanup: Iftrue, prevents the deletion of generated test files when a source YAML is removed in watch mode. Set via--no-cleanup.quick,force,no-defaults: These relate to theinitcommand for generating configuration files.
API
Global Options
testweaver supports the following global options, which can be applied before any command:
-h, --help: Display help for command-V, --version: Output the version number--verbose: Enable verbose logging for detailed output.--debug: Enable debug logging for highly detailed debugging (most verbose).--silent: Suppress all output except critical errors.
Commands
generate (Default Command)
Generates Jest-compatible test files from YAML definitions.
Arguments
[patterns...]: one or more glob patterns for yaml files. overrides config
Options
-c, --config <filename>: specify a custom configuration file to load patterns from. overrides default cascade-i, --ignore <patterns...>: list of glob file patterns to exclude from matched files. overrides config-k, --test-keyword <keyword>: specify keyword for test blocks. Allowed values: "it", "test".-n, --dry-run: perform a dry run: simulate file generation without writing to disk-o, --output-dir <path>: specify the output directory for generated test files. overrides config-w, --watch: watch for changes in yaml files and regenerate test files automatically--no-cleanup: do not delete generated .test.js files when source yaml is unlinked in watch mode
Examples
# Generate tests from all YAML files in the 'tests' directory
testweaver generate "tests/**/*.yaml"
# Generate tests from a specific YAML file and enable watch mode
testweaver generate my-feature.yaml --watch
# Generate tests using a custom configuration file and ignore specific patterns
testweaver generate -c custom-config.json -i "temp/**/*.yaml"
# Perform a dry run for all YAML files in the 'features' directory
testweaver generate "features/**/*.yml" --dry-run
# Generate tests with a custom output directory, preserving the source folder structure
# For a source file at 'tests/sample/cli.test.yaml', the output will be 'out/tests/sample/cli.test.js'
testweaver generate --output-dir outinit
Initializes a new project by creating a .testweaver.json configuration file in the current directory.
Arguments
[filename]: The name of the configuration file to create. Defaults totestweaver.json.
Options
-f, --force: Force overwrite the configuration file if it already exists.--no-defaults: Only include settings in the generated file whose values differ from the default values.-q, --quick: Skip interactive questions and generate the configuration file with default values.
Examples
# Create a default testweaver.json interactively
testweaver init
# Create a default testweaver.json without prompts
testweaver init --quick
# Create a custom config file named 'my-config.json'
testweaver init my-config.json
# Force overwrite an existing config file without prompts
testweaver init --quick --force
# Create a config file with only non-default settings
testweaver init --no-defaults🚀 Available Scripts
This repository includes a set of scripts designed to streamline development, enforce quality, and automate documentation.
Automated Documentation
npm run docs:all: A convenience script that updates all documentation sections: table of contents, available scripts, and project structure.npm run docs:scripts: Updates the "Available Scripts" section inREADME.mdwith this script.npm run docs:structure: Updates the project structure tree inREADME.md.npm run generate-schema: Generates a JSON schema for the configuration file.npm run toc: Generates a Table of Contents inREADME.mdusingdoctoc.
Code Quality & Formatting
npm run check: A convenience script that runs the linter.npm run fix: A convenience script that formats code and then fixes lint issues.npm run format: Formats all JavaScript, Markdown, and JSON files with Prettier.npm run lint: Lints all JavaScript and Markdown files using ESLint.npm run lint:fix: Automatically fixes linting issues in all JavaScript and Markdown files.
Core Development
npm run start: Runs the application usingnode src/index.js.npm run test: Runs all tests with Jest.npm run test:coverage: Runs all tests with Jest and generates a coverage report.npm run test:watch: Runs Jest in watch mode, re-running tests on file changes.
The "One-Click" Pre-Commit Workflow
npm run ready: A convenience script to run before committing: updates all documentation and then formats and fixes all files.
A Focus on Quality and Productivity
This repository is more than just a collection of files; it's a workflow designed to maximize developer productivity and enforce high-quality standards from day one. The core philosophy is to automate the tedious and error-prone tasks so you can focus on what matters: building great software.
The Cost of Stale Documentation
In many projects, the README.md quickly becomes outdated. Manually updating the project structure or list of scripts is an easily forgotten chore.
test-weaver solves this problem with its custom documentation scripts:
scripts/update-readme-structure.js: Saves you from manually drawing out file trees. What might take 5-10 minutes of careful, manual work (and is often forgotten) is now an instant, accurate, and repeatable command.scripts/update-readme-scripts.js: Ensures that your project's capabilities are always documented. It reads directly frompackage.json, so the documentation can't lie. It even reminds you to describe your scripts, promoting good habits.
The Power of Workflow Scripts
Chaining commands together is a simple but powerful concept. The fix, docs:all, and ready scripts are designed to create a seamless development experience.
- Instead of remembering to run
prettiertheneslint --fix, you just runnpm run fix. - Instead of running three separate documentation commands, you just run
npm run docs:all. - And most importantly, before you commit, you run
npm run ready. This single command is your pre-flight check. It guarantees that every commit you push is not only functional but also perfectly formatted, linted, and documented. This discipline saves countless hours in code review and prevents messy commit histories.
By embracing this automation, test-weaver helps you build better software, faster.
📦 Release & Versioning
This project uses release-please to automate releases, versioning, and changelog generation. This ensures a consistent and hands-off release process, relying on the Conventional Commits specification.
How it Works
- Conventional Commits: All changes merged into the
mainbranch should follow the Conventional Commits specification (e.g.,feat: add new feature,fix: resolve bug). - Release Pull Request:
release-pleaseruns as a GitHub Action and monitors themainbranch for new Conventional Commits. When it detects changes that warrant a new release (e.g., afeatcommit for a minor version, afixcommit for a patch version), it automatically creates a "Release PR" with a title likechore(release): 1.2.3. - Review and Merge: This Release PR contains:
- An updated
CHANGELOG.mdwith all changes since the last release. - A bumped version number in
package.json. - Proposed release notes. Review this PR, and once satisfied, merge it into
main.
- An updated
- Automated GitHub Release & Publish: Merging the Release PR triggers two final, sequential actions:
- The
release-pleaseaction creates a formal GitHub Release and a corresponding Git tag (e.g.,v1.1.0). - The creation of this release then triggers the
publish.ymlworkflow, which automatically publishes the package to the npm registry.
- The
Creating a New Release
To create subsequent releases, simply merge changes into the main branch using Conventional Commits. release-please will handle the rest by creating a Release PR. Once that PR is merged, the new version will be released automatically.
Your First Release
To bootstrap the process and create your very first release:
- Ensure your
package.jsonversion is at a sensible starting point (e.g.,1.0.0). - Make at least one commit to the
mainbranch that follows the Conventional Commits specification. A good first commit would be:feat: Initial release. - Push your commit(s) to
main. Therelease-pleaseaction will run and create your first Release PR. - Review and merge this PR. This will trigger the creation of your
v1.0.0GitHub Release and publish the package to npm.
For more details, refer to the release-please documentation.
📁 Project Structure
.
├── .github/ # GitHub Actions workflows
│ └── workflows/
│ ├── ci.yml # Continuous Integration (CI) workflow
│ ├── publish.yml
│ └── release-please.yml
├── .qodo/
│ └── testConfig.toml
├── config/
│ ├── default-config.schema.json
│ └── default.json
├── docs/
├── src/ # Source code
│ ├── commands/
│ │ ├── generate.js
│ │ └── init.js
│ ├── config/
│ │ └── configLoader.js
│ ├── core/
│ │ ├── fileProcessor.js
│ │ ├── testGenerator.js
│ │ └── watcher.js
│ ├── utils/
│ │ ├── commandLoader.js
│ │ └── logger.js
│ └── index.js # Main application entry point
├── tests/
│ ├── fileProcessor.security.test.js
│ ├── fileProcessor.test.js
│ ├── generate-output-dir.test.js
│ ├── generate.test.js
│ ├── index.test.js
│ └── testGenerator.test.js
├── .eslintignore # Files/folders for ESLint to ignore
├── .eslintrc.json # ESLint configuration
├── .gitignore # Files/folders for Git to ignore
├── .npmrc
├── .prettierignore # Files/folders for Prettier to ignore
├── .prettierrc.json # Prettier configuration
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md # Community standards
├── CONTRIBUTING.md # Guidelines for contributors
├── jest.config.js
├── LICENSE # Project license
├── package.json # Project metadata and dependencies
└── README.md # This file✍️ Linting for Documentation
This project uses the eslint-plugin-jsdoc package to enforce that all functions, classes, and methods are properly documented using JSDoc comments. This helps maintain a high level of code quality and makes the codebase easier for new and existing developers to understand.
How to Check for Missing Documentation
You can check the entire project for missing or incomplete docblocks by running the standard linting command:
npm run lintESLint will scan your JavaScript files and report any undocumented code as a warning.
Example
Consider the following function in your code without any documentation:
function calculateArea(width, height) {
return width * height;
}When you run npm run lint, ESLint will produce a warning similar to this:
/path/to/your/project/src/your-file.js
1:1 warning Missing JSDoc for function 'calculateArea' jsdoc/require-jsdocTo fix this, you would add a JSDoc block that describes the function, its parameters, and what it returns. Most modern code editors (like VS Code) can help by generating a skeleton for you if you type /** and press Enter above the function.
Corrected Code:
/**
* Calculates the area of a rectangle.
* @param {number} width The width of the rectangle.
* @param {number} height The height of the rectangle.
* @returns {number} The calculated area.
*/
function calculateArea(width, height) {
return width * height;
}After adding the docblock, running npm run lint again will no longer show the warning for this function.
🐞 Bug Reports
Found a bug? We'd love to hear about it. Please raise an issue on our GitHub Issues page.
🤝 Contributing
Contributions are welcome! Please read our contributing guidelines to get started.
🗺️ Roadmap
This project is actively maintained, and we have a clear vision for its future. Here are some of the features and improvements we are planning:
- TypeScript Support: Add a separate branch or configuration for a TypeScript version of this template.
- Monorepo Example: Provide guidance and an example setup for using this template within a monorepo structure.
- Containerization: Include a
Dockerfileanddocker-compose.ymlfor easy container-based development. - Additional CI/CD Examples: Add examples for other CI/CD providers like CircleCI or GitLab CI.
If you have ideas for other features, please open an issue to discuss them!
⚖️ Code of Conduct
To ensure a welcoming and inclusive community, this project adheres to a Code of Conduct. Please read it to understand the standards of behavior we expect from all participants.
🙏 Acknowledgements
This project was built upon the shoulders of giants. We'd like to thank the creators and maintainers of these amazing open-source tools and specifications that make this template possible:
- Node.js
- Jest
- ESLint
- Prettier
- Release Please
- Conventional Commits
- Doctoc
- eslint-plugin-jsdoc
- Keep a Changelog
- Semantic Versioning
- Contributor Covenant
👨💻 About the Author
This template was created and is maintained by Ion Gireada.
- GitHub: @ioncakephper
- Website: Feel free to add your personal website or blog here.
- LinkedIn: Connect with me on LinkedIn!
📄 License
This project is licensed under the MIT License.
