diff --git a/src/modules/helpers/index.ts b/src/modules/helpers/index.ts index 1b28ddfac34..7f056b9f3e0 100644 --- a/src/modules/helpers/index.ts +++ b/src/modules/helpers/index.ts @@ -783,7 +783,10 @@ export class Helpers { count?: number ): T[] { if (typeof count !== 'number') { - count = this.faker.datatype.number({ min: 1, max: array.length }); + count = + array.length === 0 + ? 0 + : this.faker.datatype.number({ min: 1, max: array.length }); } else if (count > array.length) { count = array.length; } else if (count < 0) { diff --git a/test/helpers.spec.ts b/test/helpers.spec.ts index e436e6dc3e7..819f08a39d4 100644 --- a/test/helpers.spec.ts +++ b/test/helpers.spec.ts @@ -543,6 +543,18 @@ describe('helpers', () => { // Check uniqueness expect(subset).toHaveLength(new Set(subset).size); }); + + it('should return an empty array when receiving an empty array', () => { + const result = faker.helpers.arrayElements([]); + + expect(result).toHaveLength(0); + }); + + it('should return an empty array when receiving an empty array and count > 0', () => { + const result = faker.helpers.arrayElements([], 3); + + expect(result).toHaveLength(0); + }); }); describe('randomize()', () => {