/
index.js
61 lines (54 loc) · 1.71 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
import context from '../../context';
import useTestCallbacks from '../../state/useTestCallbacks';
import useTestObjects from '../../state/useTestObjects';
import hasRemainingTests from '../../suite/hasRemainingTests';
import { removePending } from '../lib/pending';
/**
* Runs async test.
* @param {VestTest} testObject A VestTest instance.
*/
const runAsyncTest = testObject => {
const { asyncTest, statement } = testObject;
const { stateRef } = context.use();
const done = context.bind({ stateRef }, () => {
removePending(testObject);
// This is for cases in which the suite state was already reset
if (!stateRef.current() || testObject.canceled) {
return;
}
// Perform required done callback calls and cleanups after the test is finished
runDoneCallbacks(testObject.fieldName);
});
const fail = context.bind({ stateRef }, rejectionMessage => {
testObject.statement =
typeof rejectionMessage === 'string' ? rejectionMessage : statement;
testObject.fail();
// Spreading the array to invalidate the cache
useTestObjects(testObjects => [...testObjects]);
done();
});
try {
asyncTest.then(done, fail);
} catch (e) {
fail();
}
};
/**
* Runs done callback when async tests are finished running.
* @param {string} [fieldName] Field name with associated callbacks.
*/
const runDoneCallbacks = fieldName => {
const [{ fieldCallbacks, doneCallbacks }] = useTestCallbacks();
if (fieldName) {
if (
!hasRemainingTests(fieldName) &&
Array.isArray(fieldCallbacks[fieldName])
) {
fieldCallbacks[fieldName].forEach(cb => cb());
}
}
if (!hasRemainingTests()) {
doneCallbacks.forEach(cb => cb());
}
};
export default runAsyncTest;