Skip to content

Commit 5ea8252

Browse files
authored
feat: throw error on unknown locale (#1071)
1 parent e8985f6 commit 5ea8252

2 files changed

Lines changed: 46 additions & 2 deletions

File tree

src/faker.ts

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,34 @@ const metadataKeys: ReadonlyArray<keyof LocaleDefinition> = [
4545

4646
export class Faker {
4747
locales: UsedLocales;
48-
locale: UsableLocale;
49-
localeFallback: UsableLocale;
48+
private _locale: UsableLocale;
49+
private _localeFallback: UsableLocale;
50+
51+
get locale(): UsableLocale {
52+
return this._locale;
53+
}
54+
55+
set locale(locale: UsableLocale) {
56+
if (!this.locales[locale]) {
57+
throw new FakerError(
58+
`Locale ${locale} is not supported. You might want to add the requested locale first to \`faker.locales\`.`
59+
);
60+
}
61+
this._locale = locale;
62+
}
63+
64+
get localeFallback(): UsableLocale {
65+
return this._localeFallback;
66+
}
67+
68+
set localeFallback(localeFallback: UsableLocale) {
69+
if (!this.locales[localeFallback]) {
70+
throw new FakerError(
71+
`Locale ${localeFallback} is not supported. You might want to add the requested locale first to \`faker.locales\`.`
72+
);
73+
}
74+
this._localeFallback = localeFallback;
75+
}
5076

5177
readonly definitions: LocaleDefinition = this.initDefinitions();
5278

test/faker.spec.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,24 @@ describe('faker', () => {
3232
);
3333
});
3434

35+
it('should throw error if locale is not known', () => {
36+
const instance = new Faker({ locales: { en: { title: 'English' } } });
37+
expect(() => (instance.locale = 'unknown')).toThrow(
38+
new FakerError(
39+
'Locale unknown is not supported. You might want to add the requested locale first to `faker.locales`.'
40+
)
41+
);
42+
});
43+
44+
it('should throw error if localeFallback is not known', () => {
45+
const instance = new Faker({ locales: { en: { title: 'English' } } });
46+
expect(() => (instance.localeFallback = 'unknown')).toThrow(
47+
new FakerError(
48+
'Locale unknown is not supported. You might want to add the requested locale first to `faker.locales`.'
49+
)
50+
);
51+
});
52+
3553
it('should not log anything on startup', () => {
3654
const spies: Array<SpyInstance> = Object.keys(console)
3755
.filter((key) => typeof console[key] === 'function')

0 commit comments

Comments
 (0)