-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathuseTestsRun.ts
More file actions
86 lines (77 loc) · 2.05 KB
/
useTestsRun.ts
File metadata and controls
86 lines (77 loc) · 2.05 KB
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
import { useCallback, useState } from 'react';
import type { TestSuites } from '../types/tests';
import type { Stats, SuiteResults, TestResult } from '../types/results';
export const defaultStats = {
start: new Date(),
end: new Date(),
duration: 0,
suites: 0,
tests: 0,
passes: 0,
pending: 0,
failures: 0,
};
export const useTestsRun = (): [
SuiteResults<TestResult>,
(suites: TestSuites) => void,
] => {
const [results, setResults] = useState<SuiteResults<TestResult>>({});
const addResult = useCallback(
(newResult: TestResult) => {
setResults(prev => {
if (!prev[newResult.suiteName]) {
prev[newResult.suiteName] = { results: [] };
}
prev[newResult.suiteName]?.results.push(newResult);
return { ...prev };
});
},
[setResults],
);
const runTests = (suites: TestSuites) => {
setResults({});
run(addResult, suites);
};
return [results, runTests];
};
const run = (
addTestResult: (testResult: TestResult) => void,
suites: TestSuites = {},
) => {
const stats: Stats = { ...defaultStats };
stats.start = new Date();
Object.entries(suites).map(([suiteName, suite]) => {
stats.suites++;
Object.entries(suite.tests).map(async ([testName, test]) => {
if (!suite.value) return;
try {
await test();
stats.passes++;
addTestResult({
type: 'correct',
description: testName,
indentation: 0,
suiteName,
});
console.log(`✅ Test "${suiteName} - ${testName}" passed!`);
} catch (e: unknown) {
const err = e as Error;
stats.failures++;
addTestResult({
type: 'incorrect',
description: testName,
indentation: 0,
suiteName,
errorMsg: err.message,
});
console.log(
`❌ Test "${suiteName} - ${testName}" failed! ${err.message}`,
);
}
stats.tests++;
});
});
stats.end = new Date();
stats.duration = stats.end.valueOf() - stats.start.valueOf();
return stats;
};