Gathering detailed insights and metrics for yup-by-example
Gathering detailed insights and metrics for yup-by-example
Gathering detailed insights and metrics for yup-by-example
Gathering detailed insights and metrics for yup-by-example
npm install yup-by-example
Typescript
Module System
Min. Node Version
Node Version
NPM Version
JavaScript (100%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
11 Stars
133 Commits
1 Forks
2 Watchers
1 Branches
2 Contributors
Updated on Feb 12, 2025
Latest Version
4.0.2
Package Id
yup-by-example@4.0.2
Unpacked Size
77.75 kB
Size
18.12 kB
File Count
45
NPM Version
10.2.3
Node Version
18.19.0
Published on
Jan 30, 2024
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
1
Yup By Example is a random data generator driven from Yup schemas. For those practicing TDD, a rich and potentially shared schema increases the burden of managing test data. One solution is to create a common, hard coded set of test data, but this is almost certainly a bad idea. Not only does it lead to brittle tests, but also means that the tests come to depend on something that's often hidden away, instead of the salient values being front and centre.
Instead, by generating random sets of test data, and explicitly overwriting just the key values, the tests will be more robust and communicate far more clearly. However, maintaining random test data generators is complex and onerous. If only it could be automatically generated from the same schema used for validation. This is where Yup By Example comes in.
1const yupByExample = require('yup-by-example'); 2const { Schema, object, string, number, date, ...yup } = require('yup'); 3 4// This must be done before you build any schema that uses yup-by-example 5yup.addMethod(Schema, 'example', yupByExample); 6 7// Add .example() everywhere you want an example 8const userSchema = object({ 9 name: string().required().example(), 10 age: number().positive().integer().max(120)required().example(), 11 email: string().email()required().example(), 12 website: string().url().nullable().example(), 13 createdOn: date().default(() => new Date()).example(), 14}).example(); 15 16module.exports = { userSchema }
1const { TestDataFactory } = require('yup-by-example'); 2const schema = require('../src/userSchema'); 3 4describe('User', () => { 5 6 beforeEach() { 7 TestDataFactory.init(); 8 } 9 10 it('should create a valid user', async () => { 11 const user = await TestDataFactory.generateValid(schema); 12 console.log(user); 13 //... 14 }) 15})
1{ 2 "name": "GpxiKtlnEDBXpSX", 3 "age": 75, 4 "email": "vor@bigedac.cl", 5 "website": "http://uloero.lr/et", 6 "createdOn": "2848-04-15T06:10:26.256Z" 7}
You can use the included and custom test data generators for even more realitic test data. You can even create arrays of test data too. See the example schema for more details.
As of yup v1.0.0 adding yupByExample to yup.mixed
no longer works. Instead use
1yup.addMethod(Schema, 'example', yupByExample);
1npm i yup-by-example --save-dev
By default, Yup By Example will use the metadata type
property or schema type to automatically generate valid test data for the following rules
type | rules |
---|---|
string | length, min, max, email, url, oneOf |
number | min, max, lessThan, morethan, positive, negative, integer, oneOf |
boolean | oneOf |
date | min, max, oneOf |
array | of, length, min, max, oneOf |
object | shape, oneOf |
However for more nuanced validation and to make your data more realistic you can use one of Yup By Example's in built generators or even write your own cusotm generator (see below).
A generator which uses an inline function to return test data. The function must be supplied as the second argument, e.g.
1string().example({ generator: 'fn' }, () => { 2 const randomOctet = () => Math.floor(Math.random() * 256); 3 const ipAddress = Array.from({ length: 4 }, randomOctet).join('.'); 4 return ipAddress; 5})
The inline function will passed an object with the following parameters
name | notes |
---|---|
id | Used to namespace session properties |
session | The test data session |
chance | An instance of Chance |
A generator which delegates to the Chance library. e.g.
1string().example({ generator: 'chance' }, { 2 method: 'name', 3 params: { 4 middle_initial: true 5 }, 6});
Sometimes you don't need a random date, but an offset one.
1date().example({ generator: 'rel-date' }, { days: 1 }),
By default, the generated dates will be reletive to when you initialised the TestDataFactory. You can override this as follows...
1const { TestDataFactory } = require('yup-by-example'); 2TestDataFactory.init({ now: new Date('2000-01-01T00:00:00.000Z') });
rel-date uses date-fns add behind the scenes, and can be used to adjust the years, months, weeks, days, hours, minutes and seconds.
The Literal generator lets you specify literal examples.
1string().example({ generator: 'literal' }, 'Frank');
For even greater flexibility, you can write a custom generator. This is a object exposing a generate
function, which will be passed an object with the following parameters
name | notes |
---|---|
id | the generator id (used to namespace session properties) |
params | the generator parameters |
session | The test data session |
chance | An instance of Chance |
now | The timestamp when the TestDataFactory was initialised |
schema | The schema as supplied by yup |
value | The value as supplied by yup |
originalValue | The originalValue as supplied by yup |
The generator must also be registered with the TestDataFactory
. e.g.
1const NiNumberGenerator = { 2 generate: ({ chance }) => { 3 const start = chance.string({ length: 2 }); 4 const middle = chance.integer({ min: 100000, max 999999 }); 5 const end = chance.string({ length: 1 }); 6 return `${start}${middle}${end}`.toUpperCase(); 7 } 8}
1TestDataFactory.init().addGenerator('ni-number', NiNumberGenerator);
1string().example({ generator: 'ni-number' });
After defining the schema, there are two ways of generating test data.
Use the former when you want to generate valid test data and the latter when you need to generate a partial or invalid document.
You can optionally pass yup validation options as the second parameter.
When generating test data, you often don't want it to be completely random, instead it is often dependent on data previously generated in your test. You can communicate this information across examples by storing state in the session passed to the generator. The session exposes the following methods
You also can pre-initialise the session with values that your test generators will refer to, e.g.
1const user = object().shape({ 2 name: string().example(), 3}).example(); 4 5// Here we have given the generator an id of 'users' 6const users = array.of(user).example({ id: 'users' });
1const { TestDataFactory } = require('yup-by-example'); 2const userSchema = require('../src/userSchema'); 3 4describe('User', () => { 5 6 beforeEach() { 7 TestDataFactory.init(); 8 } 9 10 it('should create users', async () => { 11 // Here we stash a property in the session 12 TestDataFactory.session.setProperty('users.length', 4); 13 14 // Because the array generator checks for `${id}.length` it will generate exactly 4 users 15 const users = await TestDataFactory.generateValid(schemas.users); 16 17 // ... 18 }) 19})
You can reset the session at any point by calling TestDataFactory.init()
, however the session is shared, and so may prevent concurrent tests.
Whenever a generate returns a value, before yielding it, the TestDataFactory will emit the event from the current session, allowing you to read and even modify the value. The event name will be one of:
This can be especially useful when adjusting values inside arrays
1const { Schema, object, array, ...yup } = require('yup'); 2const yupByExample = require('yup-by-example'); 3 4yup.addMethod(Schema, 'example', yupByExample); 5 6const user = object().meta({ type: 'user' }).shape({ 7 dob: date().example({ id: 'dob' generator: 'rel-date' }), 8}).example(); 9 10const users = array().of(user).example();
1const { TestDataFactory } = require('yup-by-example'); 2const schemas = require('../src/schemas'); 3 4describe('User', () => { 5 6 beforeEach() { 7 TestDataFactory.init(); 8 } 9 10 it('should create users', async () => { 11 let userIndex = 0; 12 13 TestDataFactory.session.on('user', event => { 14 userIndex++; 15 }) 16 17 // Adjusts the generated dob based on the user index 18 TestDataFactory.session.on('dob', event => { 19 event.value = dateFns.add(event.value, { days: userIndex }) 20 }) 21 22 const users = await TestDataFactory.generateValid(schemas.users); 23 // ... 24 }) 25})
When you create random test data, it can be useful to repeatedly get the same "random" values for debugging purposes. When you instanciate the TestDataFactory you can pass the desired seed into the constructor.
1TestDataFactory.init({ seed: 42 })
Now repeated runs should generate exactly the same data sets.
Not all Yup validations can be reliably generated. For example there is nothing in the described schema that can be used to determine if lowercase
or uppercase
is required. With strict
validation, this could cause problems. It's likely there there may also be issues with references and conditional validation.
Lazy schemas are not supported
TypeError: The value of field could not be cast to a value that satisfies the schema type: "object".
If you see this error you have probably neglected to add all the necessary .example()
calls to your schema. Another possibilitiy is that some of your schemas were built using either stub example implementation, or a test data factory instantiated in a previous test.
TypeError: string(...).example is not a function
TypeError: number(...).example is not a function
TypeError: object(...).example is not a function
etc...
You forgot to call yup.addMethod(Schema, 'example', yupByExample)
For other problems try enabling debug
DEBUG yup-by-example:* npm t
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
6 existing vulnerabilities detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 2
Details
Reason
Found 0/30 approved changesets -- score normalized to 0
Reason
no SAST tool detected
Details
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Score
Last Scanned on 2025-07-07
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More