Skip to content

Commit 5ed963f

Browse files
vithShinigami92
andauthored
fix: force passed locales into faker constructor (#580)
Co-authored-by: Shinigami92 <chrissi92@hotmail.de>
1 parent 9fad09a commit 5ed963f

2 files changed

Lines changed: 38 additions & 4 deletions

File tree

src/faker.ts

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ export type UsableLocale = LiteralUnion<KnownLocale>;
3636
export type UsedLocales = Partial<Record<UsableLocale, LocaleDefinition>>;
3737

3838
export interface FakerOptions {
39-
locales?: UsedLocales;
39+
locales: UsedLocales;
4040
locale?: UsableLocale;
4141
localeFallback?: UsableLocale;
4242
}
@@ -81,8 +81,20 @@ export class Faker {
8181
readonly vehicle: Vehicle = new Vehicle(this);
8282
readonly word: Word = new Word(this);
8383

84-
constructor(opts: FakerOptions = {}) {
85-
this.locales = this.locales || opts.locales || {};
84+
constructor(opts: FakerOptions) {
85+
if (!opts) {
86+
throw new Error(
87+
'Options with at least one entry in locales must be provided'
88+
);
89+
}
90+
91+
if (Object.keys(opts.locales ?? {}).length === 0) {
92+
throw new Error(
93+
'At least one entry in locales must be provided in the locales parameter'
94+
);
95+
}
96+
97+
this.locales = opts.locales;
8698
this.locale = this.locale || opts.locale || 'en';
8799
this.localeFallback = this.localeFallback || opts.localeFallback || 'en';
88100

test/faker.spec.ts

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,33 @@
11
import { beforeEach, describe, expect, it } from 'vitest';
2-
import { faker } from '../src';
2+
import { faker, Faker } from '../src';
33

44
describe('faker', () => {
55
beforeEach(() => {
66
faker.locale = 'en';
77
});
88

9+
it('should throw error if no options passed', () => {
10+
expect(
11+
() =>
12+
// @ts-expect-error: mission options
13+
new Faker()
14+
).toThrow(
15+
Error('Options with at least one entry in locales must be provided')
16+
);
17+
});
18+
19+
it('should throw error if no locales passed', () => {
20+
expect(
21+
() =>
22+
// @ts-expect-error: missing locales
23+
new Faker({})
24+
).toThrow(
25+
Error(
26+
'At least one entry in locales must be provided in the locales parameter'
27+
)
28+
);
29+
});
30+
931
// This is only here for coverage
1032
// The actual test is in mersenne.spec.ts
1133
describe('seed()', () => {

0 commit comments

Comments
 (0)