-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathsuite.ts
98 lines (83 loc) · 2.52 KB
/
suite.ts
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
93
94
95
96
97
98
import fs from 'fs';
import path from 'path';
import { Suite, Event } from 'benchmark';
// @ts-expect-error `jsdom` types currently collide with `parse5` types.
import { JSDOM } from 'jsdom';
import { Script } from 'vm';
import cheerio from '../lib/index.js';
const documentDir = path.join(__dirname, 'documents');
const jQuerySrc = fs.readFileSync(
path.join(__dirname, '../node_modules/jquery/dist/jquery.slim.js'),
'utf-8'
);
const jQueryScript = new Script(jQuerySrc);
let filterRe = /./;
let cheerioOnly = false;
interface SuiteOptions<T> {
test($: typeof cheerio, data: T): void;
setup($: typeof cheerio): T;
}
export default class Suites {
filter(str: string): void {
filterRe = new RegExp(str, 'i');
}
cheerioOnly(): void {
cheerioOnly = true;
}
add<T>(name: string, fileName: string, options: SuiteOptions<T>): void {
if (!filterRe.test(name)) {
return;
}
const markup = fs.readFileSync(path.join(documentDir, fileName), 'utf8');
const suite = new Suite(name);
suite.on('start', () => {
console.log(`Test: ${name} (file: ${fileName})`);
});
suite.on('cycle', (event: Event) => {
if ((event.target as any).error) {
return;
}
console.log(`\t${String(event.target)}`);
});
suite.on('error', (event: Event) => {
console.log(`*** Error in ${event.target.name}: ***`);
console.log(`\t${(event.target as any).error}`);
console.log('*** Test invalidated. ***');
});
suite.on('complete', function (this: Suite, event: Event) {
if ((event.target as any).error) {
console.log();
return;
}
console.log(`\tFastest: ${(this.filter('fastest') as any)[0].name}\n`);
});
this._benchCheerio(suite, markup, options);
if (!cheerioOnly) {
this._benchJsDom(suite, markup, options);
} else {
suite.run();
}
}
_benchJsDom<T>(suite: Suite, markup: string, options: SuiteOptions<T>): void {
const testFn = options.test;
const dom = new JSDOM(markup, { runScripts: 'outside-only' });
jQueryScript.runInContext(dom.getInternalVMContext());
const setupData: T = options.setup(dom.window.$);
suite.add('jsdom', () => {
testFn(dom.window.$, setupData);
});
suite.run();
}
_benchCheerio<T>(
suite: Suite,
markup: string,
options: SuiteOptions<T>
): void {
const $ = cheerio.load(markup);
const testFn = options.test;
const setupData: T = options.setup($);
suite.add('cheerio', () => {
testFn($, setupData);
});
}
}