Package Exports
- fluentbuilder
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (fluentbuilder) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
FluentBuilder
FluentBuilder provides a simple way for creating data builders for your tests, with all the beauty of a good intellisense.
It's recommended to use with TypeScript and a library like Faker.Js for fake data.
Installation
Nothing new here, just npm install
npm i --save-dev fluentbuilderHow To
Let's define an interface (can be a class or anything like that)
interface Foo {
id: number,
name: string
}Then define a shape for your builder and use the from method, which receives a factory function. It will use your shape to generate your test data
const builder = new Builder<Foo>()
builder.from(() => ({ id: 1, name: 'bar' }))
builder.generate() // { id: 1, name: 'bar' }Or just use the create function
const builder = Builder.create(() => ({ id: 1, name: 'bar' }))This example is not very exciting, but if we put some Faker.Js we can do better
import * as faker from 'faker'
const builder = new Builder<Foo>()
builder.from(() => ({
id: faker.random.number(),
name: faker.name.firstName()
}))
builder.generate() // { id: 37566, name: 'Marquis' }
builder.generate() // { id: 7487, name: 'Joy' }
builder.generate(2) // [ { id: 35751, name: 'Opal' }, { id: 94291, name: 'Savion' } ]Like that, every time we call generate() we will have new data. Note the fact that if we pass a number as an argument to the generate() method, it will return an array of your type of the specified size
Fluent Style
You can define rules for each of the properties in your type
builder.ruleFor("id", () => faker.random.number())We have great intellisense/autocomplete help

With these methods it's easy to derive a class from Builder
import Builder from 'fluentbuilder'
import * as faker from 'faker'
class FooBuilder extends Builder<Foo> {
constructor(){
super()
// define basic props
this.from(() => ({
id: faker.random.number(),
name: faker.name.firstName()
}))
}
withName(name: string): this {
this.ruleFor("name", () => name);
return this
}
}
const fooBuilder = new FooBuilder()
fooBuilder.generate() // { id: 58431, name: 'Lesley' }
fooBuilder.withName("Fluffy").generate() // { id: 25927, name: 'Fluffy' }
The methods can be chained, so this is a valid approach
const fooFactory = () =>
new Builder<Foo>()
.ruleFor("id", () => faker.random.number())
.ruleFor("name", () => faker.name.firstName())
.generate()