diff --git a/src/faker.ts b/src/faker.ts index d6a288c6175..c84d77a4daf 100644 --- a/src/faker.ts +++ b/src/faker.ts @@ -45,8 +45,34 @@ const metadataKeys: ReadonlyArray = [ export class Faker { locales: UsedLocales; - locale: UsableLocale; - localeFallback: UsableLocale; + private _locale: UsableLocale; + private _localeFallback: UsableLocale; + + get locale(): UsableLocale { + return this._locale; + } + + set locale(locale: UsableLocale) { + if (!this.locales[locale]) { + throw new FakerError( + `Locale ${locale} is not supported. You might want to add the requested locale first to \`faker.locales\`.` + ); + } + this._locale = locale; + } + + get localeFallback(): UsableLocale { + return this._localeFallback; + } + + set localeFallback(localeFallback: UsableLocale) { + if (!this.locales[localeFallback]) { + throw new FakerError( + `Locale ${localeFallback} is not supported. You might want to add the requested locale first to \`faker.locales\`.` + ); + } + this._localeFallback = localeFallback; + } readonly definitions: LocaleDefinition = this.initDefinitions(); diff --git a/test/faker.spec.ts b/test/faker.spec.ts index 013f7a4e631..0d25813b40c 100644 --- a/test/faker.spec.ts +++ b/test/faker.spec.ts @@ -32,6 +32,24 @@ describe('faker', () => { ); }); + it('should throw error if locale is not known', () => { + const instance = new Faker({ locales: { en: { title: 'English' } } }); + expect(() => (instance.locale = 'unknown')).toThrow( + new FakerError( + 'Locale unknown is not supported. You might want to add the requested locale first to `faker.locales`.' + ) + ); + }); + + it('should throw error if localeFallback is not known', () => { + const instance = new Faker({ locales: { en: { title: 'English' } } }); + expect(() => (instance.localeFallback = 'unknown')).toThrow( + new FakerError( + 'Locale unknown is not supported. You might want to add the requested locale first to `faker.locales`.' + ) + ); + }); + it('should not log anything on startup', () => { const spies: Array = Object.keys(console) .filter((key) => typeof console[key] === 'function')