Skip to content

Commit 03de0f0

Browse files
committed
feat(benchmark.js-plugin): support setup and teardown
1 parent cd532fd commit 03de0f0

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

packages/benchmark.js-plugin/src/index.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,10 @@ async function runBenchmarks({
183183
benchPayload = bench.fn as CallableFunction;
184184
}
185185

186+
if (typeof bench.options.setup === "function") {
187+
await bench.options.setup();
188+
}
189+
186190
if (isAsync) {
187191
await optimizeFunction(benchPayload);
188192
await (async function __codspeed_root_frame__() {
@@ -198,6 +202,11 @@ async function runBenchmarks({
198202
Measurement.stopInstrumentation(uri);
199203
})();
200204
}
205+
206+
if (typeof bench.options.teardown === "function") {
207+
await bench.options.teardown();
208+
}
209+
201210
console.log(` ✔ Measured ${uri}`);
202211
benchmarkCompletedListeners.forEach((listener) => listener());
203212
}

packages/benchmark.js-plugin/tests/index.integ.test.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,23 @@ describe("Benchmark", () => {
104104
}
105105
}
106106
);
107+
it("should call setup and teardown", async () => {
108+
mockCore.Measurement.isInstrumented.mockReturnValue(true);
109+
const setup = jest.fn();
110+
const teardown = jest.fn();
111+
const bench = withCodSpeed(
112+
new Benchmark(
113+
"RegExpSingle",
114+
function () {
115+
/o/.test("Hello World!");
116+
},
117+
{ ...benchOptions, setup, teardown }
118+
)
119+
);
120+
await bench.run();
121+
expect(setup).toHaveBeenCalled();
122+
expect(teardown).toHaveBeenCalled();
123+
});
107124
});
108125

109126
describe("Benchmark.Suite", () => {
@@ -250,4 +267,21 @@ describe("Benchmark.Suite", () => {
250267
expect(mockCore.setupCore).toHaveBeenCalledTimes(1);
251268
expect(mockCore.teardownCore).toHaveBeenCalledTimes(1);
252269
});
270+
it("should call setup and teardown", async () => {
271+
mockCore.Measurement.isInstrumented.mockReturnValue(true);
272+
const setup = jest.fn();
273+
const teardown = jest.fn();
274+
275+
const suite = withCodSpeed(new Benchmark.Suite("thesuite")).add(
276+
"RegExpSingle",
277+
function () {
278+
/o/.test("Hello World!");
279+
},
280+
{ ...benchOptions, setup, teardown }
281+
);
282+
await suite.run();
283+
284+
expect(setup).toHaveBeenCalled();
285+
expect(teardown).toHaveBeenCalled();
286+
});
253287
});

0 commit comments

Comments
 (0)