-
-
Notifications
You must be signed in to change notification settings - Fork 85
/
index.js
92 lines (78 loc) · 2.29 KB
/
index.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import { isExcluded } from '../../hooks/exclusive';
import runWithContext from '../../lib/runWithContext';
import singleton from '../../lib/singleton';
import getSuiteState from '../state/getSuiteState';
import patch from '../state/patch';
import VestTest from './lib/VestTest';
import { setPending } from './lib/pending';
/**
* Stores test object inside suite state.
* @param {String} suiteId
* @param {VestTest} testObject
*/
const addTestToState = (suiteId, testObject) => {
patch(suiteId, state => ({
...state,
testObjects: state.testObjects.concat(testObject),
}));
};
/**
* Runs sync tests - or extracts promise.
* @param {VestTest} testObject VestTest instance.
* @returns {*} Result from test callback.
*/
const sync = testObject =>
runWithContext({ currentTest: testObject }, () => {
let result;
try {
result = testObject.testFn.apply(testObject);
} catch (e) {
result = false;
}
if (result === false) {
testObject.fail();
}
return result;
});
/**
* Registers test, if async - adds to pending array
* @param {VestTest} testObject A VestTest Instance.
*/
const register = testObject => {
addTestToState(testObject.suiteId, testObject);
// Run test callback.
// If a promise is returned, set as async and
// Move to pending list.
const result = sync(testObject);
if (typeof result?.then === 'function') {
testObject.testFn = result;
setPending(testObject.suiteId, testObject);
}
};
/**
* Test function used by consumer to provide their own validations.
* @param {String} fieldName Name of the field to test.
* @param {String} [statement] The message returned in case of a failure.
* @param {function} testFn The actual test callback.
* @return {VestTest} A VestTest instance.
*/
const test = (fieldName, ...args) => {
const { length, [length - 2]: statement, [length - 1]: testFn } = args;
const ctx = singleton.useContext();
const testObject = new VestTest({
fieldName,
group: ctx.groupName,
statement,
suiteId: ctx.suiteId,
testFn,
});
if (isExcluded(getSuiteState(ctx.suiteId), testObject)) {
return testObject;
}
if (typeof testFn !== 'function') {
return;
}
register(testObject);
return testObject;
};
export default test;