• Stars
    star
    759
  • Rank 59,846 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 6 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A library for setting up JavaScript objects as test data

Fishery

CircleCI

Fishery is a library for setting up JavaScript objects for use in tests and anywhere else you need to set up data. It is loosely modeled after the Ruby gem, factory_bot.

Fishery is built with TypeScript in mind. Factories accept typed parameters and return typed objects, so you can be confident that the data used in your tests is valid. If you aren't using TypeScript, that's fine too – Fishery still works, just without the extra typechecking that comes with TypeScript.

Installation

Install fishery with:

npm install --save-dev fishery

or

yarn add --dev fishery

Usage

A factory is just a function that returns your object. Fishery provides several arguments to your factory function to help with common situations. After defining your factory, you can then call build() on it to build your objects. Here's how it's done:

Define and use factories

// factories/user.ts
import { Factory } from 'fishery';
import { User } from '../my-types';
import postFactory from './post';

const userFactory = Factory.define<User>(({ sequence }) => ({
  id: sequence,
  name: 'Rosa',
  address: { city: 'Austin', state: 'TX', country: 'USA' },
  posts: postFactory.buildList(2),
}));

const user = userFactory.build({
  name: 'Susan',
  address: { city: 'El Paso' },
});

user.name; // Susan
user.address.city; // El Paso
user.address.state; // TX (from factory)

Asynchronously create objects with your factories

In some cases, you might want to perform an asynchronous operation when building objects, such as saving an object to the database. This can be done by calling create instead of build. First, define an onCreate for your factory that specifies the behavior of create, then create objects with create in the same way you do with build:

const userFactory = Factory.define<User>(({ onCreate }) => {
  onCreate(user => User.create(user));

  return {
    ...
  };
});

const user = await userFactory.create({ name: 'Maria' });
user.name; // Maria

create returns a promise instead of the object itself but otherwise has the same API as build. The action that occurs when calling create is specified by defining an onCreate method on your factory as described below.

create can also return a different type from build. This type can be specified when defining your factory:

Factory.define<ReturnTypeOfBuild, TransientParamsType, ReturnTypeOfCreate>

Documentation

Typechecking

Factories are fully typed, both when defining your factories and when using them to build objects, so you can be confident the data you are working with is correct.

const user = userFactory.build();
user.foo; // type error! Property 'foo' does not exist on type 'User'
const user = userFactory.build({ foo: 'bar' }); // type error! Argument of type '{ foo: string; }' is not assignable to parameter of type 'Partial<User>'.
const userFactory = Factory.define<User, UserTransientParams>(
  ({
    sequence,
    params,
    transientParams,
    associations,
    afterBuild,
    onCreate,
  }) => {
    params.firstName; // Property 'firstName' does not exist on type 'DeepPartial<User>
    transientParams.foo; // Property 'foo' does not exist on type 'Partial<UserTransientParams>'
    associations.bar; // Property 'bar' does not exist on type 'Partial<User>'

    afterBuild(user => {
      user.foo; // Property 'foo' does not exist on type 'User'
    });

    return {
      id: `user-${sequence}`,
      name: 'Bob',
      post: null,
    };
  },
);

build API

build supports a second argument with the following keys:

  • transient: data for use in your factory that doesn't get overlaid onto your result object. More on this in the Transient Params section
  • associations: often not required but can be useful in order to short-circuit creating associations. More on this in the Associations section

Use params to access passed in properties

The parameters passed in to build are automatically overlaid on top of the default properties defined by your factory, so it is often not necessary to explicitly access the params in your factory. This can, however, be useful, for example, if your factory uses the params to compute other properties:

const userFactory = Factory.define<User>(({ params }) => {
  const { name = 'Bob Smith' } = params;
  const email = params.email || `${kebabCase(name)}@example.com`;

  return {
    name,
    email,
    posts: [],
  };
});

Params that don't map to the result object (transient params)

Factories can accept parameters that are not part of the resulting object. We call these transient params. When building an object, pass any transient params in the second argument:

const user = factories.user.build({}, { transient: { registered: true } });

Transient params are passed in to your factory and can then be used however you like:

type User = {
  name: string;
  posts: Post[];
  memberId: string | null;
  permissions: { canPost: boolean };
};

type UserTransientParams = {
  registered: boolean;
  numPosts: number;
};

const userFactory = Factory.define<User, UserTransientParams>(
  ({ transientParams, sequence }) => {
    const { registered, numPosts = 1 } = transientParams;

    const user = {
      name: 'Susan Velasquez',
      posts: postFactory.buildList(numPosts),
      memberId: registered ? `member-${sequence}` : null,
      permissions: {
        canPost: registered,
      },
    };

    return user;
  },
);

In the example above, we also created a type called UserTransientParams and passed it as the second generic type to define. This gives you type checking of transient params, both in the factory and when calling build.

When constructing objects, any regular params you pass to build take precedence over the transient params:

const user = userFactory.build(
  { memberId: '1' },
  { transient: { registered: true } },
);

user.memberId; // '1'
user.permissions.canPost; // true

Passing transient params to build can be a bit verbose. It is often a good idea to consider creating a reusable builder method instead of or in addition to your transient params to make building objects simpler.

After-build hook

You can instruct factories to execute some code after an object is built. This can be useful if a reference to the object is needed, like when setting up relationships:

const userFactory = Factory.define<User>(({ sequence, afterBuild }) => {
  afterBuild(user => {
    const post = factories.post.build({}, { associations: { author: user } });
    user.posts.push(post);
  });

  return {
    id: sequence,
    name: 'Bob',
    posts: [],
  };
});

After-create hook

Similar to onCreate, afterCreates can also be defined. These are executed after the onCreate, and multiple can be defined for a given factory.

const userFactory = Factory.define<User, {}, SavedUser>(
  ({ sequence, onCreate, afterCreate }) => {
    onCreate(user => apiService.create(user));
    afterCreate(savedUser => doMoreStuff(savedUser));

    return {
      id: sequence,
      name: 'Bob',
      posts: [],
    };
  },
);

// can define additional afterCreates
const savedUser = userFactory
  .afterCreate(async savedUser => savedUser)
  .create();

Extending factories

Factories can be extended using the extension methods: params, transient, associations, afterBuild, afterCreate and onCreate. These set default attributes that get passed to the factory on build. They return a new factory and do not modify the factory they are called on :

const userFactory = Factory.define<User>(() => ({
  admin: false,
}));

const adminFactory = userFactory.params({ admin: true });
adminFactory.build().admin; // true
userFactory.build().admin; // false

params, associations, and transient behave in the same way as the arguments to build. The following are equivalent:

const user = userFactory
  .params({ admin: true })
  .associations({ post: postFactory.build() })
  .transient({ name: 'Jared' })
  .build();

const user2 = userFactory.build(
  { admin: true },
  {
    associations: { post: postFactory.build() },
    transient: { name: 'Jared' },
  },
);

Additionally, the following extension methods are available:

  • afterBuild - executed after an object is built. Multiple can be defined
  • onCreate - defines or replaces the behavior of create(). Must be defined prior to calling create(). Only one can be defined.
  • afterCreate - called after onCreate() before the object is returned from create(). Multiple can be defined

These extension methods can be called multiple times to continue extending factories:

const sallyFactory = userFactory
  .params({ admin: true })
  .params({ name: 'Sally' })
  .afterBuild(user => console.log('hello'))
  .afterBuild(user => console.log('there'));

const user = sallyFactory.build();
// log: hello
// log: there
user.name; // Sally
user.admin; // true

const user2 = sallyFactory.build({ admin: false });
user.name; // Sally
user2.admin; // false

Adding reusable builders (traits) to factories

If you find yourself frequently building objects with a certain set of properties, it might be time to either extend the factory or create a reusable builder method.

Factories are just classes, so adding reusable builder methods can be achieved by subclassing Factory and defining any desired methods:

class UserFactory extends Factory<User, UserTransientParams> {
  admin(adminId?: string) {
    return this.params({
      admin: true,
      adminId: adminId || `admin-${this.sequence()}`,
    });
  }

  registered() {
    return this
      .params({ memberId: this.sequence() })
      .transient({ registered: true })
      .associations({ profile: profileFactory.build() })
      .afterBuild(user => console.log(user))
  }
}

// instead of Factory.define<User>
const userFactory = UserFactory.define(() => ({ ... }))

const user = userFactory.admin().registered().build()

To learn more about the factory builder methods params, transient, associations, afterBuild, onCreate, and afterCreate, see Extending factories, above.

Advanced

Associations

Factories can import and reference other factories for associations:

import userFactory from './user';

const postFactory = Factory.define<Post>(() => ({
  title: 'My Blog Post',
  author: userFactory.build(),
}));

If you'd like to be able to pass in an association when building your object and short-circuit the call to yourFactory.build(), use the associations variable provided to your factory:

const postFactory = Factory.define<Post>(({ associations }) => ({
  title: 'My Blog Post',
  author: associations.author || userFactory.build(),
}));

Then build your object like this:

const jordan = userFactory.build({ name: 'Jordan' });
factories.post.build({}, { associations: { author: jordan } });

If two factories reference each other, they can usually import each other without issues, but TypeScript might require you to explicitly type your factory before exporting so it can determine the type before the circular references resolve:

// the extra Factory<Post> typing can be necessary with circular imports
const postFactory: Factory<Post> = Factory.define<Post>(() => ({ ...}));
export default postFactory;

Rewind Sequence

A factory's sequence can be rewound with rewindSequence(). This sets the sequence back to its original starting value.

Contributing

See the CONTRIBUTING document. Thank you, contributors!

Credits

This project name was inspired by Patrick Rothfuss' Kingkiller Chronicles books. In the books, the artificery, or workshop, is called the Fishery for short. The Fishery is where things are built.

License

Fishery is Copyright © 2021 Stephen Hanson and thoughtbot. It is free software, and may be redistributed under the terms specified in the LICENSE file.

About thoughtbot

Fishery is maintained and funded by thoughtbot, inc. The names and logos for thoughtbot are trademarks of thoughtbot, inc.

We love open source software! See our other projects or hire us to design, develop, and grow your product.

More Repositories

1

guides

A guide for programming in style.
Ruby
9,327
star
2

bourbon

A Lightweight Sass Tool Set
Ruby
9,100
star
3

paperclip

Easy file attachment management for ActiveRecord
Ruby
9,055
star
4

laptop

A shell script to set up a macOS laptop for web and mobile development.
Shell
8,416
star
5

dotfiles

A set of vim, zsh, git, and tmux configuration files.
Shell
7,942
star
6

factory_bot

A library for setting up Ruby objects as test data.
Ruby
7,826
star
7

administrate

A Rails engine that helps you put together a super-flexible admin dashboard.
JavaScript
5,867
star
8

neat

A fluid and flexible grid Sass framework
Ruby
4,444
star
9

suspenders

A Rails template with our standard defaults, ready to deploy to Heroku.
Ruby
3,922
star
10

til

Today I Learned
3,903
star
11

clearance

Rails authentication with email & password.
Ruby
3,629
star
12

shoulda-matchers

Simple one-liner tests for common Rails functionality
Ruby
3,513
star
13

Argo

Functional JSON parsing library for Swift
Swift
3,487
star
14

high_voltage

Easily include static pages in your Rails app.
Ruby
3,141
star
15

rcm

rc file (dotfile) management
Perl
2,990
star
16

factory_bot_rails

Factory Bot ♥ Rails
Ruby
2,972
star
17

shoulda

Makes tests easy on the fingers and the eyes
Ruby
2,196
star
18

expandable-recycler-view

Custom Android RecyclerViewAdapters that collapse and expand
Java
2,073
star
19

capybara-webkit

A Capybara driver for headless WebKit to test JavaScript web apps
Ruby
1,969
star
20

gitsh

An interactive shell for git
Ruby
1,957
star
21

Tropos

Weather and Forecasts for Humans
Swift
1,518
star
22

refills

[no longer maintained]
CSS
1,513
star
23

design-sprint

Product Design Sprint Material
1,415
star
24

bitters

Add a dash of pre-defined style to your Bourbon.
HTML
1,398
star
25

griddler

Simplify receiving email in Rails (deprecated)
Ruby
1,376
star
26

trail-map

Trails to help designers and developers learn various topics.
1,219
star
27

appraisal

A Ruby library for testing your library against different versions of dependencies.
Ruby
1,194
star
28

hotwire-example-template

A collection of branches that transmit HTML over the wire.
Ruby
1,033
star
29

parity

Shell commands for development, staging, and production parity for Heroku apps
Ruby
890
star
30

Runes

Infix operators for monadic functions in Swift
Swift
830
star
31

cocaine

A small library for doing (command) lines.
Ruby
788
star
32

flutie

View helpers for Rails applications
Ruby
730
star
33

TBAnnotationClustering

Example App: How To Efficiently Display Large Amounts of Data on iOS Maps
Objective-C
728
star
34

vim-rspec

Run Rspec specs from Vim
Vim Script
650
star
35

climate_control

Modify your ENV
Ruby
512
star
36

constable

Better company announcements
Elixir
511
star
37

carnival

An unobtrusive, developer-friendly way to add comments
Haskell
501
star
38

ruby-science

The reference for writing fantastic Rails applications
Ruby
494
star
39

Curry

Swift implementations for function currying
Swift
494
star
40

pacecar

Generated scopes for ActiveRecord classes
Ruby
437
star
41

hoptoad_notifier

Reports exceptions to Hoptoad
Ruby
408
star
42

fake_stripe

A Stripe fake so that you can avoid hitting Stripe servers in tests.
Ruby
393
star
43

json_matchers

Validate your JSON APIs
Ruby
384
star
44

Swish

Nothing but Net(working)
Swift
363
star
45

superglue

A productive library for Classic Rails, React and Redux
JavaScript
361
star
46

paul_revere

A library for "one off" announcements in Rails apps.
Ruby
298
star
47

stencil

Android library, written exclusively in kotlin, for animating the path created from text
Kotlin
282
star
48

Perform

Easy dependency injection for storyboard segues
Swift
280
star
49

upcase

Sharpen your programming skills.
Ruby
275
star
50

testing-rails

Source code for the Testing Rails book
HTML
269
star
51

proteus

[no longer maintained]
Ruby
254
star
52

Delta

Managing state is hard. Delta aims to make it simple.
Swift
246
star
53

foundry

Providing a new generation of vector assets and infinite possibility for the interactive web and mobile applications
CSS
233
star
54

limerick_rake

A collection of useful rake tasks.
Ruby
232
star
55

shoulda-context

Shoulda Context makes it easy to write understandable and maintainable tests under Minitest and Test::Unit within Rails projects or plain Ruby projects.
Ruby
231
star
56

backbone-support

lumbar support
JavaScript
227
star
57

terrapin

Run shell commands safely, even with user-supplied values
Ruby
216
star
58

Superb

Pluggable HTTP authentication for Swift.
Swift
203
star
59

jack_up

[DEPRECATED] Easy AJAX file uploading in Rails
Ruby
202
star
60

fistface

DIY @font-face web service.
Ruby
182
star
61

squirrel

Natural-looking Finder Queries for ActiveRecord
Ruby
178
star
62

sortable_table

Sort HTML tables in your Rails app.
Ruby
157
star
63

write-yourself-a-roguelike

Write Yourself A Roguelike: Ruby Edition
Ruby
155
star
64

pester

Automatically ask for a PR review
Ruby
147
star
65

jester

REST in Javascript
JavaScript
146
star
66

complexity

A command line tool to identify complex code
Rust
142
star
67

kumade

Heroku deploy tasks with test coverage (DEPRECATED, NO LONGER BEING DEVELOPED)
Ruby
137
star
68

proteus-middleman

[no longer maintained]
CSS
133
star
69

FunctionalJSON-swift

Swift
133
star
70

capybara_discoball

Spin up an external server just for Capybara
Ruby
128
star
71

tropos-android

Weather and Forecasts for Humans
Kotlin
128
star
72

ModalPresentationView

Remove the boilerplate of modal presentations in SwiftUI
Swift
125
star
73

react-native-typescript-styles-example

A template react native project for ergonomic styling structure and patterns.
TypeScript
123
star
74

vimulator

A JavaScript Vim simulator for demonstrations
JavaScript
119
star
75

bourne

[DEPRECATED] Adds test spies to mocha.
Ruby
114
star
76

formulator

A form library for Phoenix
Elixir
106
star
77

poppins

Gifs!
Objective-C
106
star
78

tailwindcss-aria-attributes

TailwindCSS variants for aria-* attributes
JavaScript
100
star
79

ghost-theme-template

A project scaffold for building ghost themes using gulp, node-sass, & autoprefixer
HTML
91
star
80

paperclip_demo

Paperclip demo application
Ruby
87
star
81

middleman-template

The base Middleman application used at thoughtbot, ready to deploy to Netlify.
CSS
86
star
82

proteus-jekyll

[no longer maintained]
CSS
84
star
83

report_card

metrics and CI are for A students.
Ruby
77
star
84

ios-sample-blender

Sample code for the Blending Modes blog post
Objective-C
76
star
85

yuri-ita

Create powerful interfaces for filtering, searching, and sorting collections of items.
Ruby
76
star
86

baccano

[no longer maintained]
HTML
74
star
87

goal-oriented-git

A practical book about using Git
HTML
73
star
88

ios-on-rails

A guide to building a Rails API and iOS app
HTML
72
star
89

art_vandelay

Art Vandelay is an importer/exporter for Rails 6.0 and higher.
Ruby
71
star
90

maybe_haskell

Programming without Null
HTML
71
star
91

redbird

A Redis adapter for Plug.Session
Elixir
70
star
92

maintaining-open-source-projects

A successful open source project is not only one that is original, solves a particular problem well, or has pristine code quality. Those are but the tip of the iceberg, which we'll thoroughly dissect with this book.
Shell
67
star
93

templates

Documentation templates for open source projects.
64
star
94

FOMObot

A slack bot to help with FOMO.
Haskell
61
star
95

BotKit

BotKit is a Cocoa Touch static library for use in iOS projects. It includes a number of helpful classes and categories that are useful during the development of an iOS application.
Objective-C
61
star
96

react-native-template

Template React Native project to be used with Cookiecutter
JavaScript
60
star
97

CombineViewModel

An implementation of the Model-View-ViewModel (MVVM) pattern using Combine.
Swift
59
star
98

flightdeck

Terraform modules for rapidly building production-grade Kubernetes clusters following SRE practices
HCL
55
star
99

design-for-developers-starter-kit

A starter project for design for developer students
CSS
54
star
100

mile_marker

Mark off HTML implementation expectations with clear signage
Ruby
53
star