Skip to content

Commit 43d1618

Browse files
committed
feat(tinybench-plugin): support afterAll, afterEach, beforeAll and beforeEach
1 parent 06cb38d commit 43d1618

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

packages/tinybench-plugin/src/index.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,15 @@ export function withCodSpeed(bench: Bench): Bench {
4747
setupCore();
4848
console.log(`[CodSpeed] running with @codspeed/tinybench v${__VERSION__}`);
4949
for (const task of bench.tasks) {
50+
// run before hooks
51+
if (task.opts.beforeAll != null) {
52+
await task.opts.beforeAll.call(task);
53+
}
54+
if (task.opts.beforeEach != null) {
55+
await task.opts.beforeEach.call(task);
56+
}
57+
58+
// run the actual benchmark, with instrumentation
5059
const uri = isCodSpeedBenchOptions(task.opts)
5160
? task.opts.uri
5261
: `${rootCallingFile}::${task.name}`;
@@ -56,6 +65,16 @@ export function withCodSpeed(bench: Bench): Bench {
5665
await task.fn();
5766
Measurement.stopInstrumentation(uri);
5867
})();
68+
69+
// run after hooks
70+
if (task.opts.afterEach != null) {
71+
await task.opts.afterEach.call(task);
72+
}
73+
if (task.opts.afterAll != null) {
74+
await task.opts.afterAll.call(task);
75+
}
76+
77+
// print results
5978
console.log(` ✔ Measured ${uri}`);
6079
}
6180
console.log(`[CodSpeed] Done running ${bench.tasks.length} benches.`);

packages/tinybench-plugin/tests/index.integ.test.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,4 +131,34 @@ describe("Benchmark.Suite", () => {
131131
);
132132
}
133133
);
134+
135+
it("should run before and after hooks", async () => {
136+
mockCore.isInstrumented.mockReturnValue(true);
137+
const beforeAll = jest.fn();
138+
const beforeEach = jest.fn();
139+
const afterEach = jest.fn();
140+
const afterAll = jest.fn();
141+
142+
await withCodSpeed(new Bench())
143+
.add(
144+
"RegExp",
145+
function () {
146+
/o/.test("Hello World!");
147+
},
148+
{ afterAll, afterEach, beforeAll, beforeEach }
149+
)
150+
.add(
151+
"RegExp2",
152+
() => {
153+
/o/.test("Hello World!");
154+
},
155+
{ afterAll, afterEach, beforeAll, beforeEach }
156+
)
157+
.run();
158+
159+
expect(beforeAll).toHaveBeenCalledTimes(2);
160+
expect(beforeEach).toHaveBeenCalledTimes(2);
161+
expect(afterEach).toHaveBeenCalledTimes(2);
162+
expect(afterAll).toHaveBeenCalledTimes(2);
163+
});
134164
});

0 commit comments

Comments
 (0)