@@ -24,6 +24,8 @@ import {
2424 toError ,
2525} from './utils'
2626
27+ 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 {
9496 this . #async = fnOpts . async ?? isFnAsyncResource ( fn )
9597 this . #signal = fnOpts . signal
9698
99+ 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+
97108 if ( this . #signal) {
98109 this . #signal. addEventListener (
99110 'abort' ,
@@ -264,7 +275,7 @@ export class Task extends EventTarget {
264275 time : number ,
265276 iterations : number
266277 ) : Promise < { error : Error , samples ?: never } | { error ?: never , samples ?: Samples } > {
267- if ( this . #fnOpts. beforeAll != null ) {
278+ if ( this . #fnOpts. beforeAll ) {
268279 try {
269280 await this . #fnOpts. beforeAll . call ( this , mode )
270281 } catch ( error ) {
@@ -350,7 +361,7 @@ export class Task extends EventTarget {
350361 time : number ,
351362 iterations : number
352363 ) : { error : Error , samples ?: never } | { error ?: never , samples ?: Samples } {
353- if ( this . #fnOpts. beforeAll != null ) {
364+ if ( this . #fnOpts. beforeAll ) {
354365 try {
355366 const beforeAllResult = this . #fnOpts. beforeAll . call ( this , mode )
356367 invariant (
@@ -370,7 +381,7 @@ export class Task extends EventTarget {
370381 return
371382 }
372383 try {
373- if ( this . #fnOpts. beforeEach != null ) {
384+ if ( this . #fnOpts. beforeEach ) {
374385 const beforeEachResult = this . #fnOpts. beforeEach . call ( this , mode )
375386 invariant (
376387 ! isPromiseLike ( beforeEachResult ) ,
@@ -383,7 +394,7 @@ export class Task extends EventTarget {
383394 samples . push ( taskTime )
384395 totalTime += taskTime
385396 } finally {
386- if ( this . #fnOpts. afterEach != null ) {
397+ if ( this . #fnOpts. afterEach ) {
387398 const afterEachResult = this . #fnOpts. afterEach . call ( this , mode )
388399 invariant (
389400 ! isPromiseLike ( afterEachResult ) ,
@@ -406,7 +417,7 @@ export class Task extends EventTarget {
406417 return { error : toError ( error ) }
407418 }
408419
409- if ( this . #fnOpts. afterAll != null ) {
420+ if ( this . #fnOpts. afterAll ) {
410421 try {
411422 const afterAllResult = this . #fnOpts. afterAll . call ( this , mode )
412423 invariant (
0 commit comments