This is in in ALPHA right now and may be subject to significant breaking changes until it stabilizes
A speck is a specification that can be used for:
- TypeScript type checking
- Run-time validation
- Generation of random test data
Under the hood it uses:
- io-ts: Combines TypeScript types with Run-time validation. VERY IMPORTANT
- fast-check: Generative testing framework.
It copies some code from:
- fast-check-io-ts: Marries
io-ts
withfast-check
.fast-check-io-ts
andspeck
have the same aim. Speck just adds the ability to define custom specifications e.g. an email specification which generates and validates emails and has TypeScript typestring
.
It is inspired by:
🐵
An example node REPL session which demonstrates runtime validation and generation of test data.
First, set-up:
> const s = require('@imin/speck');
> const Offer = s.intersection([
s.type({
type: s.literal('Offer'),
}),
s.partial({
id: s.urlString,
name: s.string,
price: s.positiveFloat,
priceCurrency: s.literal('GBP'),
}),
]);
Runtime validation:
> s.validate(Offer, {
type: 'Offer',
price: 3.4,
priceCurrency: 'GBP',
});
{ type: 'Offer', price: 3.4, priceCurrency: 'GBP' } // i.e. this is valid
> s.validate(Offer, {
type: 'Offer',
price: 'not a number',
});
{ Error: SpeckValidationErrors
// .. stack trace
errors:
[ { value: 'not a number', context: [Array] }], // i.e. there's a validation error. It is explained in detail in the context
summary: [ 'Expecting number at 1.price but instead got: "not a number"' ] } // shortened summary of the errors object
Generation of random test data
> s.gen(Offer, {
name: 'Offer #1',
});
{ type: 'Offer',
id:
'http://ebueegdadw.xnewckh2f3-y.unztjlyc/%F4%8D%86%A0An:%F2%AE%A7%84/2/,/dAy_q/Fs%F1%99%B0%A8Kn/S*muw%F4%8D%AE%88*Ny/_n%F1%89%AE%A2W',
name: 'Offer #1',
price: 39.99195694923401 }
Env vars can be used to control speck's behaviour. All are optional:
SPECK_ERROR_EXCLUDE_DETAIL
: If set totrue
, Speck Validation Errors will only include summaries - rather than very detailed error objects.
lib/index.d.ts
andlib/ioTsBrands.d.ts
are generated by TypeScript- A pre-commit hook re-builds and adds to git the above files
- Document more thoroughly
- Unit tests