json-schema-testgen
v0.2.1
Published
Generate test files from the official JSON-Schema-Test-Suite
Readme
json-schema-testgen
Generate test files from the official JSON-Schema-Test-Suite for validating JSON Schema implementations.
Supports generating tests for Bun, Vitest, and Jest.
Usage
# With npx
npx json-schema-testgen --help
# With bunx
bunx json-schema-testgen --helpGenerating tests
# Generate required tests for all drafts (default runner: bun)
npx json-schema-testgen
# Generate tests for vitest or jest
npx json-schema-testgen --runner vitest
npx json-schema-testgen --runner jest
# Generate only specific drafts
npx json-schema-testgen --drafts draft7,draft2020-12
# Include optional tests
npx json-schema-testgen --include-optional
# Custom output directory
npx json-schema-testgen --output ./my-testsCLI options
| Option | Description | Default |
|---|---|---|
| --runner <runner> | Test runner: bun, vitest, jest | bun |
| --drafts <list> | Comma-separated drafts to include | all drafts |
| --include-optional | Include optional tests | false |
| --output <dir> | Output directory | ./generated-tests |
| --version | Show version | |
| --help | Show help message | |
Plugging in your validator
Create a setup file that calls setValidator before tests run:
import { setValidator } from "json-schema-testgen";
setValidator((schema, data, draft) => {
// Return { valid: boolean, errors?: string[] }
// `draft` is e.g. "draft7", "draft2020-12"
const result = myValidator.validate(schema, data);
return { valid: result.valid, errors: result.errors };
});How you preload the setup file depends on the runner:
- Bun — add
preload = ["./setup.ts"]tobunfig.toml, thenbun test - Vitest — add
setupFiles: ["./setup.ts"]to your vitest config, thenvitest - Jest — add
setupFilesAfterFramework: ["./setup.ts"]to your jest config, thenjest
Supported drafts
draft3draft4draft6draft7draft2019-09draft2020-12
Test output
Generated tests show verbose details on failure:
Schema: {
"type": "integer"
}
Data: 1.1
Expected: invalid
Got: valid
Errors: type mismatch: expected integerDevelopment
bun install
git submodule update --init # fetch the official test suite
bun run build-data # embed test data into src/test-data.tsTo update when the upstream test suite changes:
cd official-tests && git pull origin main && cd ..
bun run build-data