TypeORM Entity factory
The library allows you to create factories for your entities. Useful when unit-testing your NestJS project.
Faker
Library using faker.js for provide fake-data in you factories.
Library has peer dependecy for faker and faker-types libraries, but make sure you have them installed. If you want take help about functions in your IDE, just install @types/faker and faker
libraries for yourself.
How to
-
Install library:
yarn add typeorm-factories
ornpm install typeorm-factories
-
Library can find factory file everywhere in project folder. But could be better if you can create folder for them:
Create folder in project root:
mkdir factories
-
Create your first factory:
;;;defineTask,;Here we have factory for
Task
entity. Entity has this interface: -
Use it everywhere:
In my case i wanted to create unit-testing of my project without database hitting. Just test it on mock data. How?
Look at my test file for my tasks controller in project:
For first we need to create
mockFactory
for repositories. Place this code everywhere you want:;// @ts-ignore;And lookup to code of test file for my controller
describe'TasksController',;As you can see, we are create entity by factory via
factory()
function. After call this we have object of typeEntityFactory
.EnityFactory
provide 3 functions:map(callback)
- callback will be called for every item in array or solo item when we callmake
ormakeMany
functions.makeMany(count, params)
- create many objects of your entity. Override default params in original object by passed params from variable.make(params)
- create one one entity object and override. About params see above.
Few words
Detailed instructions for use in development. I have not told even half of all the possibilities of this library. If you have a question about the library’s work, you can create Issue. If you have a desire to help me and make the documentation better, contact me. I have some problems with the narration and I think there are people who do it better than me.