Skip to content

Commit

Permalink
Merge branch 'next' into Add-a-documentation-page-for-how-to-use-fake…
Browse files Browse the repository at this point in the history
…r-with-testing-frameworks-faker-js#1324
  • Loading branch information
brenno263 committed Dec 7, 2022
2 parents b8906e3 + d0ff3fe commit 7c37b8d
Show file tree
Hide file tree
Showing 30 changed files with 599 additions and 173 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/commentCodeGeneration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ module.exports = async (
issue_number: context.issue.number,
});

const body = `Uncommitted changes were detected after runnning <code>generate:*</code> commands.\nPlease run <code>pnpm run generate:locales</code> and <code>pnpm run generate:api-docs</code> to generate/update the related files, and commit them.`;
const body = `Uncommitted changes were detected after runnning <code>generate:*</code> commands.\nPlease run <code>pnpm run generate:locales</code>, <code>pnpm run generate:api-docs</code>, and <code>pnpm run test -u</code> to generate/update the related files, and commit them.`;

const botComment = comments.find(
(comment) => comment.user?.type === 'Bot' && comment.body?.includes(body)
Expand Down
2 changes: 2 additions & 0 deletions .github/workflows/pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ jobs:
run: |
pnpm run generate:locales
pnpm run generate:api-docs
pnpm run build
pnpm run test -u
- name: Check diff
id: diff
Expand Down
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,12 @@ Array.from({ length: 10 }).forEach(() => {
});
```

The above code indicates a basic usage of Faker.
The point of interest is the import statements at the top.
The first import indicates how one can import the entirety of Faker, which includes every local, while the commented-out import showcases how to import only a single local.
In most situations, importing a single local is preferable for performance because some testing frameworks reload imports for every test file, which causes startup latencies to add up quickly.
Thus, limiting the import to a single locale can speed up startup times.

## 💎 Modules

An in-depth overview of the API methods is available in the [documentation](https://fakerjs.dev/guide/).
Expand Down
5 changes: 5 additions & 0 deletions docs/guide/localization.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ The English locales are around 600 KB in size.
All locales together are around 5 MB in size.
:::

:::tip Note
Some locales have limited coverage and rely more heavily on the English locale as the source for features they currently do not have.
However, in most cases, using a specific locale will be beneficial in the long term as specifying a locale reduces the time necessary for startup, which has a compounding effect on testing frameworks that reload the imports every execution.
:::

## Available locales

<!-- LOCALES-AUTO-GENERATED-START -->
Expand Down
4 changes: 4 additions & 0 deletions docs/guide/upgrading.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,7 @@ For the old `faker.datatype.number` method you should replace with `faker.number
| `faker.datatype.number` | `faker.number.int` or `faker.number.float` |
| `faker.datatype.float` | `faker.number.float` |
| `faker.datatype.bigInt` | `faker.number.bigInt` |

### `allowLeadingZeros` behavior change in `faker.string.numeric`

The `allowLeadingZeros` boolean parameter in `faker.string.numeric` (in the new `string` module) now defaults to `true`. `faker.string.numeric` will now generate numeric strings that could have leading zeros by default.
9 changes: 8 additions & 1 deletion docs/guide/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,18 @@ Using Faker is as easy as importing it from `@faker-js/faker`.

```js
import { faker } from '@faker-js/faker';

// or, if desiring only a specific locale
// import { faker } from '@faker-js/faker/locale/de'
const randomName = faker.person.fullName(); // Rowan Nikolaus
const randomEmail = faker.internet.email(); // Kassandra.Haley@erich.biz
```

:::tip Note
Using the first import statement will load every locale into memory.
As such, start-up times and performance may be slow.
Thus, by declaring a locale in the import, one can increase performance and reduce the time on start-up.
:::

Or if you're using CommonJS:

```js
Expand Down
6 changes: 3 additions & 3 deletions src/modules/color/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ export class ColorModule {
color = formatHexColor(color, options);
return color;
}
color = Array.from({ length: 3 }).map(() => this.faker.number.int(255));
color = Array.from({ length: 3 }, () => this.faker.number.int(255));
if (includeAlpha) {
color.push(this.faker.number.float({ max: 1, precision: 0.01 }));
cssFunction = 'rgba';
Expand Down Expand Up @@ -380,7 +380,7 @@ export class ColorModule {
*/
cmyk(options?: { format?: ColorFormat }): string | number[];
cmyk(options?: { format?: ColorFormat }): string | number[] {
const color: string | number[] = Array.from({ length: 4 }).map(() =>
const color: string | number[] = Array.from({ length: 4 }, () =>
this.faker.number.float({ max: 1, precision: 0.01 })
);
return toColorFormat(color, options?.format || 'decimal', 'cmyk');
Expand Down Expand Up @@ -742,7 +742,7 @@ export class ColorModule {
if (options?.format === 'css' && !options?.space) {
options = { ...options, space: 'sRGB' };
}
const color = Array.from({ length: 3 }).map(() =>
const color = Array.from({ length: 3 }, () =>
this.faker.number.float({ max: 1, precision: 0.0001 })
);
return toColorFormat(
Expand Down
13 changes: 10 additions & 3 deletions src/modules/datatype/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,16 +278,23 @@ export class DatatypeModule {
* Returns an array with random strings and numbers.
*
* @param length Size of the returned array. Defaults to `10`.
* @param length.min The minimum size of the array.
* @param length.max The maximum size of the array.
*
* @example
* faker.datatype.array() // [ 94099, 85352, 'Hz%T.C\\l;8', '|#gmtw3otS', '2>:rJ|3$&d', 56864, 'Ss2-p0RXSI', 51084, 2039, 'mNEU[.r0Vf' ]
* faker.datatype.array(3) // [ 61845, 'SK7H$W3:d*', 'm[%7N8*GVK' ]
* faker.datatype.array({ min: 3, max: 5 }) // [ 99403, 76924, 42281, "Q'|$&y\\G/9" ]
*
* @since 5.5.0
*/
array(length = 10): Array<string | number> {
return Array.from<string | number>({ length }).map(() =>
this.boolean() ? this.faker.string.sample() : this.faker.number.int()
array(
length: number | { min: number; max: number } = 10
): Array<string | number> {
return this.faker.helpers.multiple(
() =>
this.boolean() ? this.faker.string.sample() : this.faker.number.int(),
{ count: length }
);
}

Expand Down
26 changes: 20 additions & 6 deletions src/modules/date/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,20 +331,28 @@ export class DateModule {
* // ]
* faker.date.betweens({ from: '2020-01-01T00:00:00.000Z', to: '2030-01-01T00:00:00.000Z', count: 2 })
* // [ 2023-05-02T16:00:00.000Z, 2026-09-01T08:00:00.000Z ]
* faker.date.betweens({ from: '2020-01-01T00:00:00.000Z', to: '2030-01-01T00:00:00.000Z', count: { min: 2, max: 5 }})
* // [
* // 2021-12-19T06:35:40.191Z,
* // 2022-09-10T08:03:51.351Z,
* // 2023-04-19T11:41:17.501Z
* // ]
*
* @since 8.0.0
*/
betweens(options: {
from: string | Date | number;
to: string | Date | number;
count?: number;
count?: number | { min: number; max: number };
}): Date[];
/**
* Generates random dates between the given boundaries.
*
* @param from The early date boundary.
* @param to The late date boundary.
* @param count The number of dates to generate. Defaults to `3`.
* @param count.min The minimum number of dates to generate.
* @param count.max The maximum number of dates to generate.
*
* @example
* faker.date.betweens('2020-01-01T00:00:00.000Z', '2030-01-01T00:00:00.000Z')
Expand Down Expand Up @@ -384,6 +392,12 @@ export class DateModule {
* // ]
* faker.date.betweens({ from: '2020-01-01T00:00:00.000Z', to: '2030-01-01T00:00:00.000Z', count: 2 })
* // [ 2023-05-02T16:00:00.000Z, 2026-09-01T08:00:00.000Z ]
* faker.date.betweens({ from: '2020-01-01T00:00:00.000Z', to: '2030-01-01T00:00:00.000Z', count: { min: 2, max: 5 }})
* // [
* // 2021-12-19T06:35:40.191Z,
* // 2022-09-10T08:03:51.351Z,
* // 2023-04-19T11:41:17.501Z
* // ]
*
* @since 8.0.0
*/
Expand All @@ -395,7 +409,7 @@ export class DateModule {
| {
from: string | Date | number;
to: string | Date | number;
count?: number;
count?: number | { min: number; max: number };
},
legacyTo?: string | Date | number,
legacyCount?: number
Expand All @@ -408,7 +422,7 @@ export class DateModule {
| {
from: string | Date | number;
to: string | Date | number;
count?: number;
count?: number | { min: number; max: number };
},
legacyTo?: string | Date | number,
legacyCount: number = 3
Expand All @@ -425,9 +439,9 @@ export class DateModule {

const { from, to, count = 3 } = options;

return Array.from({ length: count }, () => this.between({ from, to })).sort(
(a, b) => a.getTime() - b.getTime()
);
return this.faker.helpers
.multiple(() => this.between({ from, to }), { count })
.sort((a, b) => a.getTime() - b.getTime());
}

/**
Expand Down
31 changes: 30 additions & 1 deletion src/modules/helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -539,7 +539,7 @@ export class HelpersModule {
* faker.helpers.fake('Good Morning {{person.firstName}}!') // 'Good Morning Estelle!'
* faker.helpers.fake('You can call me at {{phone.number(!## ### #####!)}}.') // 'You can call me at 202 555 973722.'
* faker.helpers.fake('I flipped the coin and got: {{helpers.arrayElement(["heads", "tails"])}}') // 'I flipped the coin and got: tails'
* faker.helpers.fake('I rolled the dice and got: {{string.numeric(1, {"allowLeadingZeros": true})}}') // 'I rolled the dice and got: 6'
* faker.helpers.fake('Your PIN number is: {{string.numeric(4, {"exclude": ["0"]})}}') // 'Your PIN number is: 4834'
*
* @since 7.4.0
*/
Expand Down Expand Up @@ -690,4 +690,33 @@ export class HelpersModule {
currentIterations: 0,
});
}

/**
* Generates an array containing values returned by the given method.
*
* @param method The method used to generate the values.
* @param options The optional options object.
* @param options.count The number or range of elements to generate. Defaults to `3`.
*
* @example
* faker.helpers.multiple(faker.person.firstName) // [ 'Aniya', 'Norval', 'Dallin' ]
* faker.helpers.multiple(faker.person.firstName, { count: 3 }) // [ 'Santos', 'Lavinia', 'Lavinia' ]
*
* @since 8.0.0
*/
multiple<T>(
method: () => T,
options: {
count?: number | { min: number; max: number };
} = {}
): T[] {
const count = this.rangeToNumber(options.count ?? 3);
if (count <= 0) {
return [];
}

// TODO @ST-DDT 2022-11-21: Add support for unique option

return Array.from({ length: count }, method);
}
}
50 changes: 10 additions & 40 deletions src/modules/internet/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -387,16 +387,9 @@ export class InternetModule {
* @since 6.1.1
*/
ipv4(): string {
const randNum = () => {
return this.faker.number.int(255).toFixed(0);
};

const result: string[] = [];
for (let i = 0; i < 4; i++) {
result[i] = randNum();
}

return result.join('.');
return Array.from({ length: 4 }, () => this.faker.number.int(255)).join(
'.'
);
}

/**
Expand All @@ -408,36 +401,13 @@ export class InternetModule {
* @since 4.0.0
*/
ipv6(): string {
const randHash = () => {
let result = '';
for (let i = 0; i < 4; i++) {
result += this.faker.helpers.arrayElement([
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'a',
'b',
'c',
'd',
'e',
'f',
]);
}
return result;
};

const result: string[] = [];
for (let i = 0; i < 8; i++) {
result[i] = randHash();
}
return result.join(':');
return Array.from({ length: 8 }, () =>
this.faker.string.hexadecimal({
length: 4,
casing: 'lower',
prefix: '',
})
).join(':');
}

/**
Expand Down
20 changes: 6 additions & 14 deletions src/modules/lorem/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,8 @@ export class LoremModule {
* @since 2.0.1
*/
words(wordCount: number | { min: number; max: number } = 3): string {
wordCount = this.faker.helpers.rangeToNumber(wordCount);

return Array.from({ length: wordCount })
.map(() => this.word())
return this.faker.helpers
.multiple(() => this.word(), { count: wordCount })
.join(' ');
}

Expand Down Expand Up @@ -141,10 +139,8 @@ export class LoremModule {
sentenceCount: number | { min: number; max: number } = { min: 2, max: 6 },
separator: string = ' '
): string {
sentenceCount = this.faker.helpers.rangeToNumber(sentenceCount);

return Array.from({ length: sentenceCount })
.map(() => this.sentence())
return this.faker.helpers
.multiple(() => this.sentence(), { count: sentenceCount })
.join(separator);
}

Expand Down Expand Up @@ -202,10 +198,8 @@ export class LoremModule {
paragraphCount: number | { min: number; max: number } = 3,
separator: string = '\n'
): string {
paragraphCount = this.faker.helpers.rangeToNumber(paragraphCount);

return Array.from({ length: paragraphCount })
.map(() => this.paragraph())
return this.faker.helpers
.multiple(() => this.paragraph(), { count: paragraphCount })
.join(separator);
}

Expand Down Expand Up @@ -267,8 +261,6 @@ export class LoremModule {
lines(
lineCount: number | { min: number; max: number } = { min: 1, max: 5 }
): string {
lineCount = this.faker.helpers.rangeToNumber(lineCount);

return this.sentences(lineCount, '\n');
}
}
2 changes: 2 additions & 0 deletions src/modules/number/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ export class NumberModule {
*
* @throws When options define `max < min`.
*
* @see faker.string.numeric() If you would like to generate a `string` of digits with a given length (range).
*
* @example
* faker.number.int() // 55422
* faker.number.int(100) // 52
Expand Down

0 comments on commit 7c37b8d

Please sign in to comment.