forked from jquense/yup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.js
62 lines (51 loc) · 1.52 KB
/
helpers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import printValue from '../src/util/printValue';
export let castAndShouldFail = (schema, value) => {
(() => schema.cast(value)).should.throw(
TypeError,
/The value of (.+) could not be cast to a value that satisfies the schema type/gi,
);
};
export let castAll = (inst, { invalid = [], valid = [] }) => {
valid.forEach(([value, result, schema = inst]) => {
it(`should cast ${printValue(value)} to ${printValue(result)}`, () => {
expect(schema.cast(value)).to.equal(result);
});
});
invalid.forEach(value => {
it(`should not cast ${printValue(value)}`, () => {
castAndShouldFail(inst, value);
});
});
};
export let validateAll = (inst, { valid = [], invalid = [] }) => {
describe('valid:', () => {
runValidations(valid, true);
});
describe('invalid:', () => {
runValidations(invalid, false);
});
function runValidations(arr, isValid) {
arr.forEach(config => {
let message = '',
value = config,
schema = inst;
if (Array.isArray(config)) [value, schema, message = ''] = config;
it(`${printValue(value)}${message && ` (${message})`}`, () =>
schema.isValid(value).should.become(isValid));
});
}
};
export function ensureSync(fn) {
let run = false;
let resolve = t => {
if (!run) return t;
throw new Error('Did not execute synchronously');
};
let err = t => {
if (!run) throw t;
throw new Error('Did not execute synchronously');
};
let result = fn().then(resolve, err);
run = true;
return result;
}