TypeScript ObjectMother (ts-object-mother)
An ObjectMother support library to facilitate the easy creation of builders in TypeScript
Install
npm install @makerx/ts-object-mother --save-dev
Usage
The first step is to define a model
type Colour = 'Blue' | 'Red' | 'Yellow' | 'Green'
export type Shape = {
name: string
sides: number
colour: Colour
}
Then define a builder for that model
import { randomElement, randomNumberBetween, randomString } from '@makerx/ts-object-mother'
import { DataBuilder, proxyBuilder } from '@makerx/ts-object-mother'
import { Shape } from './shape'
class ShapeBuilder extends DataBuilder<Shape> {
constructor() {
super({
name: randomString(10, 20),
sides: randomNumberBetween(1, 4),
colour: randomElement(['Blue', 'Red', 'Yellow', 'Green']),
})
}
public withName(name: string) {
return this.with('name', name + ' Intercepted')
}
}
export const shapeBuilder = proxyBuilder<ShapeBuilder, Shape>(ShapeBuilder)
Then define a mother to build known models for testing
import { shapeBuilder } from './shape-builder'
export const shapeMother = {
square: () => {
return shapeBuilder().withName('Square').withSides(4).withColour('Blue')
},
triangle: () => {
return shapeBuilder().withName('Triangle').withSides(3).withColour('Green')
},
}
And write some tests
import { describe, expect, it } from '@jest/globals'
import { shapeMother } from './shape-mother'
describe('The square', () => {
it('has four sides', () => {
const shape = shapeMother.square().build()
expect(shape.sides).toBe(4)
})
it('is named correctly', () => {
const shape = shapeMother.square().build()
expect(shape.name).toBe('Square Intercepted')
})
it('is coloured blue', () => {
const shape = shapeMother.square().build()
expect(shape.colour).toBe('Blue')
})
})
Try it out on StackBlitz