Use factories in tests #1271
Unanswered
GonzaloGPF
asked this question in
Q&A
Replies: 1 comment
-
Well, I found a way to do it. I created a helper in tests/helpers/useFactory.ts import { SeederFactoryItem, useSeederFactory } from 'typeorm-extension';
import { ObjectType, Repository } from 'typeorm';
import { TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { faker } from '@faker-js/faker';
export const useFactory = (module: TestingModule) => {
const getRepository = <T>(entity: ObjectType<T>) => {
return module.get<Repository<T>>(getRepositoryToken(entity));
};
const make = <T>(factoryItem: SeederFactoryItem) => {
return factoryItem.factoryFn(faker, { module }) as T;
};
const create = async <T>(entity: ObjectType<T>, params: Partial<T> = {}) => {
const data = await useSeederFactory(entity).make(params);
return await getRepository(entity).save(data);
};
return {
getRepository,
make,
create,
};
}; So, you can use make() in order to instantiate a model (useful in unit tests) For example: let user: User;
beforeEach(() => {
const testingModule = Test.createTestingModule(...);
user = useFactory(testModule.testingModule).create(User);
}); Problem with this is that it wont create relationships.... I would like a way to get a smart enough factory that create needed relations recursively when needed. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hi! Thanks for this awesome package, I really like it!
However, I have a question: How could I use factories in a test?
I would like to simplify entities instantiation in my tests using factories.
Something like this would be great:
Would it be possible?
Thanks!
Beta Was this translation helpful? Give feedback.
All reactions