Create a gist now

Instantly share code, notes, and snippets.

@typeetfunc /specJest Secret
Last active Nov 10, 2016

What would you like to do?
import { isArray, isBoolean, isString, isPlainObject, isUndefined, keys } from 'lodash';
import { gen } from 'jest-check';
const makeSpecable = (makeNotRequired, makeInvariant) => specable => {
const notRequired = makeNotRequired(specable);
notRequired.isRequired = specable;
notRequired.invariant = func => makeInvariant(specable, func);
return notRequired;
};
const specGen = makeSpecable(
generator => gen.oneOf([gen.undefined, generator]),
(generator, func) => gen.map(func, generator)
);
export const genSpec = {
string: specGen(gen.asciiString),
bool: specGen(gen.boolean),
oneOf: list => specGen(gen.returnOneOf(list)),
shape: shape => specGen(gen.object(shape)),
arrayOf: itemSpec => specGen(gen.array(itemSpec))
};
const specJest = makeSpecable(
check => actual => isUndefined(actual) || check(actual),
(check, func) => actual => {
expect(func(actual)).toEqual(actual);
check(actual);
}
);
export const jestSpec = {
string: specJest(actual => expect(isString(actual)).toBe(true)),
bool: specJest(actual => expect(isBoolean(actual)).toBe(true)),
oneOf: list => specJest(actual => expect(list).toContainEqual(actual)),
shape: shape => specJest(actual => {
expect(isPlainObject(actual)).toBe(true);
keys(shape).forEach(key => {
shape[key](actual[key]);
});
}),
arrayOf: itemSpec => specJest(actual => {
expect(isArray(actual)).toBe(true);
actual.forEach(item => itemSpec(item));
})
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment