feat: throw error if provided hooks are not functions (#390) · tinylibs/tinybench@3c59c54
@@ -24,6 +24,8 @@ import {
2424toError,
2525} from './utils'
262627+const hookNames = ['afterAll', 'beforeAll', 'beforeEach', 'afterEach'] as const
28+2729/**
2830 * A class that represents each benchmark task in Tinybench. It keeps track of the
2931 * results, name, the task function, the number times the task function has been executed, ...
@@ -94,6 +96,15 @@ export class Task extends EventTarget {
9496this.#async = fnOpts.async ?? isFnAsyncResource(fn)
9597this.#signal = fnOpts.signal
969899+for (const hookName of hookNames) {
100+if (this.#fnOpts[hookName] != null) {
101+invariant(
102+typeof this.#fnOpts[hookName] === 'function',
103+`'${hookName}' must be a function if provided`
104+)
105+}
106+}
107+97108if (this.#signal) {
98109this.#signal.addEventListener(
99110'abort',
@@ -264,7 +275,7 @@ export class Task extends EventTarget {
264275time: number,
265276iterations: number
266277): Promise<{ error: Error, samples?: never } | { error?: never, samples?: Samples }> {
267-if (this.#fnOpts.beforeAll != null) {
278+if (this.#fnOpts.beforeAll) {
268279try {
269280await this.#fnOpts.beforeAll.call(this, mode)
270281} catch (error) {
@@ -350,7 +361,7 @@ export class Task extends EventTarget {
350361time: number,
351362iterations: number
352363): { error: Error, samples?: never } | { error?: never, samples?: Samples } {
353-if (this.#fnOpts.beforeAll != null) {
364+if (this.#fnOpts.beforeAll) {
354365try {
355366const beforeAllResult = this.#fnOpts.beforeAll.call(this, mode)
356367invariant(
@@ -370,7 +381,7 @@ export class Task extends EventTarget {
370381return
371382}
372383try {
373-if (this.#fnOpts.beforeEach != null) {
384+if (this.#fnOpts.beforeEach) {
374385const beforeEachResult = this.#fnOpts.beforeEach.call(this, mode)
375386invariant(
376387!isPromiseLike(beforeEachResult),
@@ -383,7 +394,7 @@ export class Task extends EventTarget {
383394samples.push(taskTime)
384395totalTime += taskTime
385396} finally {
386-if (this.#fnOpts.afterEach != null) {
397+if (this.#fnOpts.afterEach) {
387398const afterEachResult = this.#fnOpts.afterEach.call(this, mode)
388399invariant(
389400!isPromiseLike(afterEachResult),
@@ -406,7 +417,7 @@ export class Task extends EventTarget {
406417return { error: toError(error) }
407418}
408419409-if (this.#fnOpts.afterAll != null) {
420+if (this.#fnOpts.afterAll) {
410421try {
411422const afterAllResult = this.#fnOpts.afterAll.call(this, mode)
412423invariant(