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

fix: force passed locales into faker constructor #580

Merged
merged 10 commits into from
Mar 28, 2022
18 changes: 15 additions & 3 deletions src/faker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export type UsableLocale = LiteralUnion<KnownLocale>;
export type UsedLocales = Partial<Record<UsableLocale, LocaleDefinition>>;

export interface FakerOptions {
locales?: UsedLocales;
locales: UsedLocales;
locale?: UsableLocale;
localeFallback?: UsableLocale;
}
Expand Down Expand Up @@ -81,8 +81,20 @@ export class Faker {
readonly vehicle: Vehicle = new Vehicle(this);
readonly word: Word = new Word(this);

constructor(opts: FakerOptions = {}) {
this.locales = this.locales || opts.locales || {};
constructor(opts: FakerOptions) {
if (!opts) {
throw new Error(
'Options with at least one entry in locales must be provided'
);
}
Shinigami92 marked this conversation as resolved.
Show resolved Hide resolved

if (Object.keys(opts.locales ?? {}).length === 0) {
throw new Error(
'At least one entry in locales must be provided in the locales parameter'
);
}

this.locales = opts.locales;
this.locale = this.locale || opts.locale || 'en';
this.localeFallback = this.localeFallback || opts.localeFallback || 'en';

Expand Down
24 changes: 23 additions & 1 deletion test/faker.spec.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,33 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { faker } from '../src';
import { faker, Faker } from '../src';

describe('faker', () => {
beforeEach(() => {
faker.locale = 'en';
});

it('should throw error if no options passed', () => {
expect(
() =>
// @ts-expect-error: mission options
new Faker()
).toThrow(
Error('Options with at least one entry in locales must be provided')
);
});

it('should throw error if no locales passed', () => {
expect(
() =>
// @ts-expect-error: missing locales
new Faker({})
).toThrow(
Error(
'At least one entry in locales must be provided in the locales parameter'
)
);
});

// This is only here for coverage
// The actual test is in mersenne.spec.ts
describe('seed()', () => {
Expand Down