From 0974ede5d2582da26503676f6f5f34515abdc80e Mon Sep 17 00:00:00 2001 From: mizdra Date: Wed, 30 Aug 2023 17:32:16 +0900 Subject: [PATCH] implement `.buildList()` --- src/factory.ts | 23 ++++++++++++++++++ src/index.test.ts | 60 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+) diff --git a/src/factory.ts b/src/factory.ts index 5316325..d877554 100644 --- a/src/factory.ts +++ b/src/factory.ts @@ -35,6 +35,13 @@ export interface TypeFactoryInterface< build>( inputFieldsResolver: T, ): Promise, ResolvedFields>, keyof Type>>; + buildList( + count: number, + ): Promise, ResolvedFields<{}>>, keyof Type>[]>; + buildList>( + count: number, + inputFieldsResolver: T, + ): Promise, ResolvedFields>, keyof Type>[]>; use( traitName: T, ): TypeFactoryInterface, _Traits>; @@ -67,6 +74,22 @@ export function defineTypeFactoryInternal< inputFieldsResolver ?? ({} as T), ); }, + async buildList>( + count: number, + inputFieldsResolver?: T, + ): Promise, ResolvedFields>, keyof Type>[]> { + const array: Pick, ResolvedFields>, keyof Type>[] = []; + for (let i = 0; i < count; i++) { + if (inputFieldsResolver) { + // eslint-disable-next-line no-await-in-loop, @typescript-eslint/no-explicit-any + array.push((await this.build(inputFieldsResolver)) as any); + } else { + // eslint-disable-next-line no-await-in-loop, @typescript-eslint/no-explicit-any + array.push((await this.build()) as any); + } + } + return array; + }, use( traitName: T, ): TypeFactoryInterface< diff --git a/src/index.test.ts b/src/index.test.ts index 9c7f5a8..d2b2b78 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -653,6 +653,66 @@ describe('TypeFactoryInterface', () => { expect(lastNameResolver).toHaveBeenCalledTimes(1); }); }); + describe('buildList', () => { + it('overrides defaultFields', async () => { + const BookFactory = defineBookFactory({ + defaultFields: { + id: lazy(({ seq }) => `Book-${seq}`), + title: 'ゆゆ式', + author: undefined, + }, + }); + // input field is optional + const books1 = await BookFactory.buildList(2); + expect(books1).toStrictEqual([ + { + id: 'Book-0', + title: 'ゆゆ式', + author: undefined, + }, + { + id: 'Book-1', + title: 'ゆゆ式', + author: undefined, + }, + ]); + assertType< + { + id: string; + title: string; + author: undefined; + }[] + >(books1); + expectTypeOf(books1).not.toBeNever(); + + BookFactory.resetSequence(); + + // Passing input fields allows overriding the default field. + const book2 = await BookFactory.buildList(2, { + title: 'ゆゆ式 100巻', + }); + expect(book2).toStrictEqual([ + { + id: 'Book-0', + title: 'ゆゆ式 100巻', + author: undefined, + }, + { + id: 'Book-1', + title: 'ゆゆ式 100巻', + author: undefined, + }, + ]); + assertType< + { + id: string; + title: string; + author: undefined; + }[] + >(book2); + expectTypeOf(book2).not.toBeNever(); + }); + }); describe('resetSequence', () => { it('resets sequence', async () => { const BookFactory = defineBookFactory({