Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions packages/tinybench-plugin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,15 @@ export function withCodSpeed(bench: Bench): Bench {
setupCore();
console.log(`[CodSpeed] running with @codspeed/tinybench v${__VERSION__}`);
for (const task of bench.tasks) {
// run before hooks
if (task.opts.beforeAll != null) {
await task.opts.beforeAll.call(task);
}
if (task.opts.beforeEach != null) {
await task.opts.beforeEach.call(task);
}

// run the actual benchmark, with instrumentation
const uri = isCodSpeedBenchOptions(task.opts)
? task.opts.uri
: `${rootCallingFile}::${task.name}`;
Expand All @@ -56,6 +65,16 @@ export function withCodSpeed(bench: Bench): Bench {
await task.fn();
Measurement.stopInstrumentation(uri);
})();

// run after hooks
if (task.opts.afterEach != null) {
await task.opts.afterEach.call(task);
}
if (task.opts.afterAll != null) {
await task.opts.afterAll.call(task);
}

// print results
console.log(` ✔ Measured ${uri}`);
}
console.log(`[CodSpeed] Done running ${bench.tasks.length} benches.`);
Expand Down
30 changes: 30 additions & 0 deletions packages/tinybench-plugin/tests/index.integ.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,4 +131,34 @@ describe("Benchmark.Suite", () => {
);
}
);

it("should run before and after hooks", async () => {
mockCore.isInstrumented.mockReturnValue(true);
const beforeAll = jest.fn();
const beforeEach = jest.fn();
const afterEach = jest.fn();
const afterAll = jest.fn();

await withCodSpeed(new Bench())
.add(
"RegExp",
function () {
/o/.test("Hello World!");
},
{ afterAll, afterEach, beforeAll, beforeEach }
)
.add(
"RegExp2",
() => {
/o/.test("Hello World!");
},
{ afterAll, afterEach, beforeAll, beforeEach }
)
.run();

expect(beforeAll).toHaveBeenCalledTimes(2);
expect(beforeEach).toHaveBeenCalledTimes(2);
expect(afterEach).toHaveBeenCalledTimes(2);
expect(afterAll).toHaveBeenCalledTimes(2);
});
});