Skip to content

Instantly share code, notes, and snippets.

@maapteh
Last active March 25, 2021 18:04
Show Gist options
  • Save maapteh/44084dac9f15e31588e6a119693c8d41 to your computer and use it in GitHub Desktop.
Save maapteh/44084dac9f15e31588e6a119693c8d41 to your computer and use it in GitHub Desktop.
typescripted builder for mocks, making the differentations easy while working
```
// thanks to Olga
const merge = require('deepmerge');
type DeepPartial<T> = T extends object
? { [K in keyof T]?: DeepPartial<T[K]> }
: T;
export type TBuilder<O> = (attrs?: DeepPartial<O>) => O;
const overwriteMerge = <T extends any>(
destinationArray: T[],
sourceArray: T[],
): T[] => sourceArray;
export const builderFor = <O extends {}>(defaults: O): TBuilder<O> => attrs =>
merge(defaults, attrs || {}, { arrayMerge: overwriteMerge });
```
Now mocking becomes easy, you create a base and add differentations on them. They are all typed
```
export const ProductBuilder = builderFor<Product>({
id: 350395,
control: {
theme: ProductTheme.FOO,
type: ProductControlType.DEFAULT,
},
title: 'Mexicaanse kip met salsa',
link:
'/mexicaanse-kip-met-salsa',
availabilityLabel: { text: 'Niet meer bestelbaar' },
orderable: false,
propertyIcons: [],
images: [
{
height: 200,
width: 200,
url:
'000089582_001_350395_200.jpg?options=399,q85'
},
{
height: 708,
width: 708,
url:
'000089580_001_350395_708.jpg?options=399,q85'
},
],
price: { now: 9.95, unitSize: '2 personen' },
theme: ProductTheme.BAR,
selectLabel: '2 personen',
hqId: 643434345,
gtins: [0, 4534534553],
brand: 'Foo',
summary: 'summary',
availableOnline: true,
});
const PRODUCT_NOT_AVAILABLE_ONLINE = ProductBuilder({
id: 48340,
availableOnline: false,
});
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment