Skip to content

Factories ​

Introduction ​

When you test an application or seed a development database, you need lots of realistic rows without writing each one by hand. A model factory describes how to build one valid row of a model, and then lets you ask for one, ten, or a hundred of them, in variations you name once and reuse. Factories are the usual way to build data for tests and for seeders.

ts
import { defineFactory, factoryFor } from '@plinthjs/orm'

Factories are immutable: count(), state() and the other builder methods return a new factory, so one base factory can be shared and specialized freely. No data generator is bundled. The definition receives the zero-based index, which is enough to build unique values, and you can use any generator you like inside it.

The examples use this setup:

ts
import { Schema, sqliteConnection } from '@plinthjs/database'
import { ConnectionDataSource, Model } from '@plinthjs/orm'

const db = sqliteConnection()
Model.connection = db
Model.dataSource = new ConnectionDataSource(db)

const schema = new Schema(db)
await schema.create('users', (table) => {
  table.id()
  table.string('name')
  table.string('email')
  table.boolean('is_admin').default(false)
  table.string('status').default('active')
  table.timestamps()
})
await schema.create('posts', (table) => {
  table.id()
  table.integer('user_id')
  table.string('title')
  table.boolean('published').default(false)
  table.timestamps()
})

class Post extends Model {
  static override table = 'posts'
  static override relations = {
    author: (model: Model) => model.belongsTo(User, 'user_id'),
  }
}

class User extends Model {
  static override table = 'users'
  static override relations = {
    posts: (model: Model) => model.hasMany(Post, 'user_id'),
  }
}

Defining Factories ​

defineFactory(Model, definition) takes a model class and a function from the instance index to its default attributes:

ts
const userFactory = defineFactory(User, (index) => ({
  name: `User ${index + 1}`,
  email: `user${index + 1}@example.com`,
}))

const postFactory = defineFactory(Post, (index) => ({
  title: `Post ${index + 1}`,
  published: false,
}))

The factory is also registered for its model. Anywhere you have the model class, factoryFor(User) returns the same factory, and throws No factory has been defined for [User]. if there is none. A convenient place for definitions is a database/factories module that your tests and seeders import.

Factories fill models with forceFill(), so fillable and guarded do not apply to factory attributes.

Creating Models ​

make() builds unsaved models and create() saves them. Both return an array with one model per count() (one by default). makeOne() and createOne() return a single model.

ts
const [user] = userFactory.make()
user.exists // => false
user.getAttribute('name') // => 'User 1'

const saved = await userFactory.createOne()
saved.exists // => true

userFactory.makeOne({ name: 'Custom' }).getAttribute('name') // => 'Custom'

Set the number of models with count(n), or use makeMany(n) and createMany(n):

ts
const users = await userFactory.count(3).create()
users.length // => 3
users.map((u) => u.getAttribute('email'))
// => ['user1@example.com', 'user2@example.com', 'user3@example.com']

await userFactory.createMany(2)
userFactory.makeMany(2)

Every builder takes an object of overrides, applied last:

ts
await userFactory.count(2).create({ status: 'invited' })

raw() and rawOne() return just the attribute objects, handy for request bodies in tests:

ts
userFactory.rawOne({ status: 'raw' })
// => { name: 'User 1', email: 'user1@example.com', status: 'raw' }
userFactory.count(2).raw() // an array of two attribute objects

The index keeps counting ​

The index handed to the definition is a running counter per factory: it continues across calls, so two separate createOne() calls build User 1 and User 2 and a unique column such as email never collides. make(), create(), raw() and their one-model forms all draw from it, and every factory derived from the same defineFactory() call (through count(), state() and so on) shares it.

ts
const first = await userFactory.createOne() // name: 'User 1'
const second = await userFactory.createOne() // name: 'User 2'

userFactory.resetSequence() // the next model is 'User 1' again

Call resetSequence() between tests that assert on generated values. To build one model at a fixed index without moving the counter, pass the index explicitly: userFactory.makeOne({}, 40). The outputs shown elsewhere on this page assume a fresh sequence.

Factory States ​

A state is a named variation. state() merges attributes over the definition. Pass an object, or a function that receives the attributes built so far and the index:

ts
const adminFactory = userFactory.state({ is_admin: true })
adminFactory.makeOne().getAttribute('is_admin') // => true

const suspendedFactory = userFactory.state((attributes, index) => ({
  status: 'suspended',
  name: `${attributes.name} (suspended)`,
}))
suspendedFactory.makeOne().getAttribute('name') // => 'User 1 (suspended)'

States apply in order, so later ones win, and they chain with each other and with count():

ts
await adminFactory.state({ status: 'invited' }).count(5).create()

For reuse, keep states next to the definition:

ts
export const users = {
  base: userFactory,
  admin: userFactory.state({ is_admin: true }),
  suspended: userFactory.state({ status: 'suspended' }),
}

Sequences ​

sequence() cycles through attribute sets by index, so the i-th model gets set i % sets.length. Each entry is an object or a function of the index:

ts
const mixed = await userFactory
  .count(4)
  .sequence({ status: 'active' }, { status: 'suspended' })
  .create()
// statuses: active, suspended, active, suspended

userFactory
  .count(2)
  .sequence((index) => ({ email: `seq${index}@example.com` }))
  .make()

Factory Callbacks ​

afterMaking() runs after a model is built, and afterCreating() after it is saved. Both receive the model. On the create() path every callback is awaited, in order.

ts
const withWelcomePost = userFactory.afterCreating(async (user) => {
  await postFactory.for(user).create()
})

await withWelcomePost.createOne()

afterMaking() also runs for make() and makeOne(), but those are synchronous, so a promise returned there is not awaited (and a rejection would be unhandled). Keep afterMaking() callbacks that you want to run through make() synchronous, or use create(), which awaits them. Children built by has() are also made on the awaited path, so an async afterMaking() on a child factory finishes before the child is saved.

Factory Relationships ​

Factories can create related models as well as the main one.

Belongs to ​

for(parent, relation?) associates every created model with a parent through a belongsTo relation. The parent can be a saved model, or a factory, in which case one parent is created and shared by the whole batch:

ts
const author = await userFactory.createOne()

const posts = await postFactory.count(3).for(author).create()
posts.map((post) => post.getAttribute('user_id')) // => [author id, author id, author id]

// Create the parent from a factory, naming the relation.
await postFactory.count(2).for(userFactory, 'author').create()

When you omit the relation name, it is inferred as the only belongsTo on the child that targets the parent's model. If there are none or several matches, the call throws and asks for an explicit name.

Has many ​

has(factory, relation?) creates children after the parent is saved. Use count() on the child factory to control how many:

ts
const user = await userFactory.has(postFactory.count(2)).createOne()
await Post.where('user_id', user.getKey()).count() // => 2

The relation is again inferred from the model classes (the only hasMany or hasOne targeting the child model), or named as a second argument: has(postFactory, 'posts'). You can call has() more than once to build several kinds of children.

Child factories can carry their own states:

ts
const published = postFactory.state({ published: true }).count(3)
await userFactory.has(published, 'posts').createOne()

Many to many ​

Factories do not manage pivot rows. Create the models, then attach them with the relation (this assumes User defines a roles relation, see Relationships), in an afterCreating callback if you want it automatic:

ts
import type { BelongsToMany } from '@plinthjs/orm'

const withRoles = userFactory.afterCreating(async (user) => {
  await (user.relation('roles') as BelongsToMany).attach([1, 2])
})

Using Factories in Tests ​

Create a fresh in-memory database for each test so factories never leak state between tests, and use factoryFor() from helpers that only know the model:

ts
import { beforeEach, expect, it } from 'vitest'

beforeEach(async () => {
  const connection = sqliteConnection()
  Model.connection = connection
  Model.dataSource = new ConnectionDataSource(connection)
  await createTables(connection)
})

it('lists published posts', async () => {
  await postFactory.state({ published: true }).count(2).create()
  await postFactory.count(1).create()

  expect(await Post.where('published', true).count()).toBe(2)
})

Here createTables stands for your own schema setup, such as running your migrations (see Migrations).

Released under the MIT License.