Skip to content

Commit

Permalink
fix: force passed locales into faker constructor (#580)
Browse files Browse the repository at this point in the history
Co-authored-by: Shinigami92 <chrissi92@hotmail.de>
  • Loading branch information
vith and Shinigami92 committed Mar 28, 2022
1 parent 9fad09a commit 5ed963f
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
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'
);
}

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

0 comments on commit 5ed963f

Please sign in to comment.