Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: throw error on unknown locale #1071

Merged
merged 1 commit into from
Jun 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 28 additions & 2 deletions src/faker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,34 @@ const metadataKeys: ReadonlyArray<keyof LocaleDefinition> = [

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();

Expand Down
18 changes: 18 additions & 0 deletions test/faker.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<SpyInstance> = Object.keys(console)
.filter((key) => typeof console[key] === 'function')
Expand Down