Skip to content

Commit

Permalink
Support defining the type when extending a factory with params()
Browse files Browse the repository at this point in the history
  • Loading branch information
lo1tuma committed Sep 9, 2021
1 parent 6bbde37 commit 5bd7aaa
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
37 changes: 37 additions & 0 deletions lib/__tests__/factory-builders.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,11 @@ describe('associations', () => {
});

describe('params', () => {
interface AdminUser extends User {
admin: true;
adminPrivileges: string[];
}

it('adds parameters that are then used for build', () => {
const user = userFactory.params({ admin: true }).build();
expect(user.admin).toBe(true);
Expand All @@ -226,6 +231,38 @@ describe('params', () => {
expect(adminFactory.build().admin).toBe(true);
expect(adminFactory.build().admin).toBe(true);
});

it('adds parameters for a sub-type which are then also accepted in build()', () => {
const adminFactory = userFactory.params<AdminUser>({
admin: true,
adminPrivileges: ['any-privilege'],
});

expect(adminFactory.build()).toEqual({
admin: true,
adminId: null,
adminPrivileges: ['any-privilege'],
firstName: 'Yussef',
id: '1',
lastName: 'Sanchez',
memberId: null,
post: { id: '1' },
registered: false,
});
expect(
adminFactory.build({ adminPrivileges: ['changed-privilege'] }),
).toEqual({
admin: true,
adminId: null,
adminPrivileges: ['changed-privilege'],
firstName: 'Yussef',
id: '1',
lastName: 'Sanchez',
memberId: null,
post: { id: '1' },
registered: false,
});
});
});

describe('transient', () => {
Expand Down
6 changes: 4 additions & 2 deletions lib/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,10 +124,12 @@ export class Factory<T, I = any> {
* @param params
* @returns a new factory
*/
params(params: DeepPartial<T>): this {
params<TOverride extends T = T>(
params: DeepPartial<TOverride>,
): Factory<TOverride, I> {
const factory = this.clone();
factory._params = merge({}, this._params, params, mergeCustomizer);
return factory;
return factory as unknown as Factory<TOverride, I>;
}

/**
Expand Down

0 comments on commit 5bd7aaa

Please sign in to comment.