Skip to content

Commit a641210

Browse files
committed
Improve documentation and formatting
1 parent 8b7e81e commit a641210

File tree

8 files changed

+112
-108
lines changed

8 files changed

+112
-108
lines changed

.github/workflows/publish.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,4 @@ jobs:
1616
- uses: actions/checkout@v4
1717

1818
- name: Publish package
19-
run: npx jsr publish --allow-slow-types
19+
run: npx jsr publish

CONTRIBUTING.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ I've tried to set a minumum Test-Driven Development (TDD) flow. Before making an
2121
1. Write a failing test first
2222
2. Run tests to verify it fails (`deno test --watch`)
2323
3. Implement the minimum code to make it pass
24-
5. Refactor if needed
24+
4. Refactor if needed
2525

2626
## Pull Request Process
2727

README.md

Lines changed: 25 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1-
# Quick Mock Data Generator
1+
# Quick Mock Data Generator
22

33
Need test data quickly? This lightweight utility helps you generate realistic mock data in seconds. Choose from common properties like names, emails, and dates, **or define your own generators**. Perfect for prototypes, tests, and demos where you need meaningful data fast.
44

55
Built on top of `@faker-js/faker`, it provides a simpler interface while maintaining type safety and full TypeScript support.
66

77
Key features:
8+
89
- 🚀 Quick property selection from common data types
910
- 🎯 Generate exactly what you need, nothing more
1011
- 📦 Zero configuration required
@@ -35,49 +36,49 @@ The `getMocksWith` function allows you to pick from a predefined set of common p
3536

3637
This basically returns a function that will create mock data based on a list of predefined properties.
3738

38-
3939
```typescript
40-
import { getMocksWith } from "@functions/mock";
40+
import { getMocksWith } from '@functions/mock'
4141

4242
// Autosuggestion will let you pick the properties you want in your mock objects
43-
const createRandomUsers = getMocksWith(['name', 'age', 'email']);
43+
const createRandomUsers = getMocksWith(['name', 'age', 'email'])
4444

4545
// Generate 3 users with only those properties
46-
const users = createRandomUsers(3);
46+
const users = createRandomUsers(3)
4747
```
4848

4949
### Generate Mock Data from a Generator
5050

5151
The `getMocksFromGenerator` function lets you define your own data generation logic. You provide an object where each property is a function that generates values. You can mix and match:
52+
5253
- Faker.js functions
5354
- Your own custom functions
5455
- Random value generators
5556
- Fixed value functions
5657
- Any JavaScript/TypeScript function that returns a value
5758

5859
```typescript
59-
import { getMocksFromGenerator } from "@functions/mock";
60-
import { faker } from "@faker-js/faker";
60+
import { getMocksFromGenerator } from '@functions/mock'
61+
import { faker } from '@faker-js/faker'
6162

6263
const yourGenerator = {
63-
// Use faker functions directly
64-
id: faker.string.uuid,
65-
// Your own random logic
66-
age: () => Math.floor(Math.random() * 100),
67-
// Mix calculated and faker values
68-
username: () => `user_${faker.number.int(1000)}`,
69-
// Fixed values
70-
role: () => 'user',
71-
// Complex custom logic
72-
status: () => {
73-
const statuses = ['active', 'inactive', 'pending'];
74-
return statuses[Math.floor(Math.random() * statuses.length)];
75-
}
76-
};
77-
78-
const createRandomObjects = getMocksFromGenerator(yourGenerator);
64+
// Use faker functions directly
65+
id: faker.string.uuid,
66+
// Your own random logic
67+
age: () => Math.floor(Math.random() * (100 - 18 + 1)) + 18,
68+
// Mix calculated and faker values
69+
username: () => `user_${faker.number.int(1000)}`,
70+
// Fixed values
71+
role: () => 'user',
72+
// Complex custom logic
73+
status: () => {
74+
const statuses = ['active', 'inactive', 'pending']
75+
return statuses[Math.floor(Math.random() * statuses.length)]
76+
},
77+
}
78+
79+
const createRandomObjects = getMocksFromGenerator(yourGenerator)
7980
// TypeScript should infers return types from your generator functions
80-
const objects = createRandomObjects(5);
81+
const objects = createRandomObjects(5)
8182
// objects is typed as Array<{ id: string; name: string; age: number }>
8283
```
8384

deno.json

Lines changed: 29 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,31 @@
11
{
2-
"name": "@functions/mock",
3-
"description": "Lightweight utility to generate realistic mock data for tests fast.",
4-
"version": "1.1.0",
5-
"license": "MIT",
6-
"exports":"./mod.ts",
7-
"tasks": {
8-
"dev": "deno run --watch main.ts"
9-
},
10-
"imports": {
11-
"@faker-js/faker": "npm:@faker-js/faker@^9.4.0",
12-
"@std/assert": "jsr:@std/assert@1"
13-
},
14-
"lint": {
15-
"rules": {
16-
"exclude": [
17-
"prefer-const",
18-
"no-unused-vars",
19-
"no-explicit-any",
20-
"ban-types"
21-
]
22-
}
23-
}
2+
"name": "@functions/mock",
3+
"description": "Lightweight utility to generate realistic mock data for tests fast.",
4+
"version": "1.1.1",
5+
"license": "MIT",
6+
"exports": "./mod.ts",
7+
"tasks": {
8+
"dev": "deno run --watch main.ts"
9+
},
10+
"imports": {
11+
"@faker-js/faker": "npm:@faker-js/faker@^9.4.0",
12+
"@std/assert": "jsr:@std/assert@1"
13+
},
14+
"lint": {
15+
"rules": {
16+
"exclude": [
17+
"prefer-const",
18+
"no-unused-vars",
19+
"no-explicit-any",
20+
"ban-types"
21+
]
22+
}
23+
},
24+
"fmt": {
25+
"useTabs": true,
26+
"lineWidth": 125,
27+
"semiColons": false,
28+
"singleQuote": true,
29+
"proseWrap": "preserve"
30+
}
2431
}

main_test.ts

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,21 @@
1-
import { assertEquals, assertExists, assertGreater, assertInstanceOf, assertLess } from "@std/assert";
1+
import { assertEquals, assertExists, assertGreater, assertInstanceOf, assertLess } from '@std/assert'
22

3-
import { getMocksFromGenerator } from "./utils/get-mocks-from-gen.ts";
4-
import { getMocksWith } from "./utils/get-mocks-with.ts"
3+
import { getMocksFromGenerator } from './utils/get-mocks-from-gen.ts'
4+
import { getMocksWith } from './utils/get-mocks-with.ts'
55
import { faker } from '@faker-js/faker'
66

7-
8-
Deno.test("Get Mocks from custom generator", () => {
9-
7+
Deno.test('Get Mocks from custom generator', () => {
108
let generator = {
119
name: faker.person.firstName,
1210
surname: faker.person.lastName,
1311
bio: faker.person.bio,
1412
email: faker.internet.email,
15-
age: () => faker.helpers.rangeToNumber({min:18,max:99}),
16-
birthday: faker.date.birthdate
13+
age: (): number => Math.floor(Math.random() * (100 - 18 + 1)) + 18,
14+
// age: () => faker.helpers.rangeToNumber({ min: 18, max: 99 }),
15+
birthday: faker.date.birthdate,
1716
}
1817

19-
let generateUser = getMocksFromGenerator( generator )
18+
let generateUser = getMocksFromGenerator(generator)
2019
let user = generateUser(1)
2120

2221
assertInstanceOf(user, Array)
@@ -25,18 +24,18 @@ Deno.test("Get Mocks from custom generator", () => {
2524

2625
assertExists(user[0].age)
2726
assertGreater(user[0].age, 17)
28-
});
27+
})
2928

30-
Deno.test("Get Mocks from specific list", () => {
31-
let generateUser = getMocksWith(['name','email','birthdate','id', 'age'])
29+
Deno.test('Get Mocks from specific list', () => {
30+
let generateUser = getMocksWith(['name', 'email', 'birthdate', 'id', 'age'])
3231
let user = generateUser(1)[0]
3332
// user has 5 props
34-
assertEquals(Object.keys(user).length, 5 )
33+
assertEquals(Object.keys(user).length, 5)
3534

3635
// age is a number
3736
assertGreater(user.age, 17)
38-
assertLess(user.age,100)
39-
37+
assertLess(user.age, 100)
38+
4039
// birthday is a Date
4140
assertInstanceOf(user.birthdate, Date)
4241
})

mod.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
export { getMocksFromGenerator } from "./utils/get-mocks-from-gen.ts";
2-
export { getMocksWith } from "./utils/get-mocks-with.ts";
1+
export { getMocksFromGenerator } from './utils/get-mocks-from-gen.ts'
2+
export { getMocksWith } from './utils/get-mocks-with.ts'

utils/get-mocks-from-gen.ts

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,21 @@
1-
2-
type MockType = <T extends Record<string,() => any> >(gen: T) => ( num?: number) => Array<{ [K in keyof T]: ReturnType<T[K]> }>
1+
type TMock = <T extends Record<string, () => any>>(g: T) => (n?: number) => { [K in keyof T]: ReturnType<T[K]> }[]
32
/**
4-
* Generate an array of random objects from your generator:
3+
* Generate an array of random objects from your generator:
54
* Fake objects will have every key as a prop, its value will be the result of its callback
6-
*
7-
* USAGE:
8-
* import { faker } from '@faker-js/faker'
9-
* const yourGenerator = { id: faker.number.int, name: faker.string.firstName, age: Math.random // TODO }
10-
* const yourObjects = getMocksFromGenerator(yourGenerator, 5)
11-
*/
12-
export const getMocksFromGenerator: MockType = gen => ( num = 1 ) => {
13-
14-
const genRandomObj = () => Object.entries(gen).reduce((obj, [prop, callback]) => {
15-
obj[prop] = callback()
16-
return obj
17-
}, Object.create(null))
5+
*
6+
* @example Basic Usage:
7+
* ```ts
8+
* import { faker } from '@faker-js/faker'
9+
* const yourGenerator = { name: faker.string.firstName, age: () => Math.floor(Math.random() * 100 ) }
10+
* const yourObjects = getMocksFromGenerator(yourGenerator, 5)
11+
* ```
12+
*/
13+
export const getMocksFromGenerator: TMock = (gen) => (num = 1) => {
14+
const genRandomObj = () =>
15+
Object.entries(gen).reduce((obj, [prop, callback]) => {
16+
obj[prop] = callback()
17+
return obj
18+
}, Object.create(null))
1819

1920
return Array.from({ length: num }, genRandomObj)
2021
}

utils/get-mocks-with.ts

Lines changed: 24 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,43 @@
11
import { faker } from '@faker-js/faker'
2-
import { getMocksFromGenerator } from "./get-mocks-from-gen.ts"
2+
import { getMocksFromGenerator } from './get-mocks-from-gen.ts'
33

44
const uniGenerator = {
5-
id: faker.string.uuid,
6-
owner_id: faker.string.uuid,
7-
name: faker.person.firstName,
8-
age: (): number => faker.number.int({ min: 18, max: 99 }),
9-
username: faker.internet.username,
10-
email: faker.internet.email,
11-
avatar: faker.image.avatar,
12-
password: faker.internet.password,
13-
birthdate: faker.date.birthdate,
14-
registeredAt: faker.date.past,
15-
last_modified: faker.date.recent,
16-
timestamp: faker.date.past,
5+
id: faker.string.uuid,
6+
owner_id: faker.string.uuid,
7+
name: faker.person.firstName,
8+
age: (): number => faker.number.int({ min: 18, max: 99 }),
9+
username: faker.internet.username,
10+
email: faker.internet.email,
11+
avatar: faker.image.avatar,
12+
password: faker.internet.password,
13+
birthdate: faker.date.birthdate,
14+
registeredAt: faker.date.past,
15+
last_modified: faker.date.recent,
16+
timestamp: faker.date.past,
1717
}
1818

1919
type Generator = typeof uniGenerator
2020
type GenKeys = keyof Generator
21-
type GetGenCallableFn = <T extends GenKeys>( props: Array<T> ) => {[K in T]: Generator[K]}
22-
21+
type GetGenCallableFn = <T extends GenKeys>(props: Array<T>) => { [K in T]: Generator[K] }
2322

2423
const getGenerator: GetGenCallableFn = (props) => {
25-
return props.reduce((acc,curr) => ({...acc, [curr]:uniGenerator[curr]}), Object.create(null) )
24+
return props.reduce((acc, curr) => ({ ...acc, [curr]: uniGenerator[curr] }), Object.create(null))
2625
}
2726

28-
type GetMocksCallableFn = <T extends GenKeys>(props: Array<T>) => (num:number) => Array<{[K in T]: ReturnType<Generator[K]>}>
27+
type GetMocksCallableFn = <T extends GenKeys>(p: T[]) => (n: number) => Array<{ [K in T]: ReturnType<Generator[K]> }>
2928
/**
3029
* Generate the random function to create your mock object/s based on a list of properties
31-
* It preserves type safety and autocompletion
32-
*
33-
* Usage:
34-
* const props = ['name', 'age', 'email']
35-
* const createRandomUsers = generateMocksFrom(props)
36-
* console.log( createRandomUsers(3) )
30+
* It preserves type safety and autocompletion.
31+
*
32+
* @example Basic Usage:
33+
* ```ts
34+
* const props = ['name', 'age', 'email']
35+
* const createRandomUsers = generateMocksFrom(props)
36+
* console.log( createRandomUsers(3) ) // [{name:string, age:number, email: string}, ...]
37+
* ```
3738
*/
3839
export const getMocksWith: GetMocksCallableFn = (properties) => getMocksFromGenerator(getGenerator(properties))
3940

40-
41-
42-
43-
4441
/* OLD Implementation with Map
4542
// @ts-ignore
4643
const generator = new Map([
@@ -66,4 +63,3 @@ const createGenerator = <T extends GenKeys>(properties: Array<T> ): {[K in T]:ty
6663
}
6764
6865
export const getMocksWith = (props: Array<GenKeys>) => getMocksFromGenerator( createGenerator(props) ) */
69-

0 commit comments

Comments
 (0)