Skip to content

Instantly share code, notes, and snippets.

@typeetfunc
Last active November 10, 2016 18:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save typeetfunc/ac4ed98d5014870c797ce138796f5cc4 to your computer and use it in GitHub Desktop.
Save typeetfunc/ac4ed98d5014870c797ce138796f5cc4 to your computer and use it in GitHub Desktop.
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