{"id":13168,"library":"factory-girl-ts","title":"Factory Girl TypeScript","description":"factory-girl-ts is a dedicated TypeScript library designed for generating test data, serving as a modern, actively maintained alternative to the unmaintained factory-girl package. Currently at version 2.3.1, it sees a steady release cadence with minor feature additions and bug fixes every few weeks to months. Its core purpose is to streamline the creation of complex test data, especially for projects utilizing popular ORMs such as Sequelize, TypeORM, and MikroORM, for which it provides dedicated adapters. Key differentiators include its TypeScript-first design, intuitive API for defining factories and managing associations, and robust support for asynchronous data creation operations, making it highly suitable for database-backed tests. The library supports both repository and active record patterns, offering flexibility in how test models are instantiated and persisted.","status":"active","version":"2.3.1","language":"javascript","source_language":"en","source_url":"https://github.com/thiagomini/factory-girl-ts","tags":["javascript","test","factory","typescript"],"install":[{"cmd":"npm install factory-girl-ts","lang":"bash","label":"npm"},{"cmd":"yarn add factory-girl-ts","lang":"bash","label":"yarn"},{"cmd":"pnpm add factory-girl-ts","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"FactoryGirl is a named export. ESM-only usage is expected for Node.js environments >= 18.16.0.","wrong":"import FactoryGirl from 'factory-girl-ts';\nconst FactoryGirl = require('factory-girl-ts');","symbol":"FactoryGirl","correct":"import { FactoryGirl } from 'factory-girl-ts';"},{"note":"Adapters like SequelizeAdapter are named exports from the main package and are used to integrate with specific ORMs.","wrong":"const { SequelizeAdapter } = require('factory-girl-ts');","symbol":"SequelizeAdapter","correct":"import { SequelizeAdapter } from 'factory-girl-ts';"},{"note":"The define method is a static method on the FactoryGirl class, not a top-level export.","wrong":"define(User, defaultAttributesFactory);","symbol":"define factory","correct":"FactoryGirl.define(User, defaultAttributesFactory);"}],"quickstart":{"code":"import { User } from './models/user';\nimport { FactoryGirl, SequelizeAdapter } from 'factory-girl-ts';\n\n// A dummy User model for demonstration purposes\nclass User {\n  id!: number;\n  name!: string;\n  email!: string;\n  address!: { state: string; country: string };\n\n  // Mimic Sequelize's static methods\n  static build(attributes: Partial<User>): User { return Object.assign(new User(), attributes); }\n  static async create(attributes: Partial<User>): Promise<User> { \n    console.log('Creating user in DB:', attributes);\n    const user = Object.assign(new User(), attributes);\n    user.id = Math.floor(Math.random() * 1000) + 1; // Simulate ID from DB\n    return Promise.resolve(user);\n  }\n}\n\n// Step 1: Specify the adapter for your ORM.\n// For actual Sequelize usage, ensure SequelizeAdapter is correctly configured with a model.\nFactoryGirl.setAdapter(new SequelizeAdapter());\n\n// Step 2: Define your factory with default attributes for the model.\nconst defaultAttributesFactory = () => ({\n  name: 'John',\n  email: 'some-email@mail.com',\n  address: {\n    state: 'Some state',\n    country: 'Some country',\n  },\n});\nconst userFactory = FactoryGirl.define(User, defaultAttributesFactory);\n\n// Step 3: Use the factory to create instances of the model.\nasync function runExample() {\n  const defaultUser = await userFactory.build();\n  console.log('Built default user:', defaultUser);\n\n  const createdUser = await userFactory.create({ email: 'new-user@example.com' });\n  console.log('Created user in DB:', createdUser);\n\n  const manyUsers = await userFactory.createMany(2, { name: 'Bulk User' });\n  console.log('Created many users:', manyUsers);\n}\n\nrunExample();","lang":"typescript","description":"This quickstart demonstrates how to set up `factory-girl-ts` with a mock Sequelize model, define a factory with default attributes, and use its `build`, `create`, and `createMany` methods to generate test data."},"warnings":[{"fix":"Rewrite existing factories to use `factory-girl-ts`'s API, import paths, and adapter patterns. Consult the `factory-girl-ts` documentation for new syntax.","message":"Users migrating from the original 'factory-girl' package should be aware that 'factory-girl-ts' is a separate, modern rewrite. It is not a drop-in replacement and requires a full migration of existing factory definitions due to API and internal implementation differences.","severity":"breaking","affected_versions":"N/A (applies when switching from 'factory-girl' to 'factory-girl-ts')"},{"fix":"Always use the `await` keyword when calling `factory.build()`, `factory.create()`, and their 'Many' counterparts to ensure operations complete synchronously within an `async` context.","message":"All factory instance methods like `build()`, `create()`, `buildMany()`, and `createMany()` are asynchronous and return Promises. Failing to `await` these calls will lead to unhandled promise rejections or tests completing before data is ready.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Review any custom adapter implementations or factory definitions that previously utilized 'additional parameters type' and refactor them to remove or replace the deprecated typing.","message":"The `additional parameters type` feature was removed in v2.2.0, which might impact custom adapter implementations or advanced factory configurations that relied on this specific typing for additional parameters.","severity":"breaking","affected_versions":">=2.2.0"},{"fix":"Ensure your project is configured for ESM, typically by setting `\"type\": \"module\"` in your `package.json` or by using `.mjs` file extensions. Use `import { NamedExport } from 'package'` syntax.","message":"`factory-girl-ts` is designed for modern JavaScript environments (Node.js >=18.16.0), implying a preference for ECMAScript Modules (ESM). Using CommonJS `require()` for imports will not work correctly for its named exports.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Upgrade to `factory-girl-ts` version 2.3.1 or higher to resolve the issue where factories might create unintended associations during definition or initial use.","message":"Prior to v2.3.1, a bug could cause factories to inadvertently create unused initial associations, potentially leading to unnecessary database operations or test data pollution.","severity":"gotcha","affected_versions":"<2.3.1"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Use named import syntax: `import { FactoryGirl } from 'factory-girl-ts';`","cause":"Incorrect import syntax for named exports, often trying to `require()` or use a default import instead of a named import.","error":"TypeError: FactoryGirl.define is not a function"},{"fix":"Always use `await` when calling factory methods, e.g., `const user = await userFactory.create();`.","cause":"Forgetting to `await` asynchronous factory methods like `build()` or `create()` within an `async` function.","error":"UnhandledPromiseRejectionWarning: Promise { <pending> }"},{"fix":"Review your ORM model's type definition and ensure it is compatible with the `new () => Model` constructor signature. You might need to adjust your model's class or use type assertions if ORM types are complex.","cause":"Type mismatch when defining factories for ORM models; the constructor signature or instantiation type for the model class does not align with `factory-girl-ts`'s expectations for 'new'able types.","error":"TS2345: Argument of type 'typeof User' is not assignable to parameter of type 'new () => User'."},{"fix":"Ensure `FactoryGirl.define()` for the target model is called and executed *before* any `build()` or `create()` operations are invoked on that factory.","cause":"Attempting to use a factory (e.g., `userFactory.create()`) before it has been properly `define`d with `FactoryGirl.define()`.","error":"Error: 'User' factory is not defined."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":""}