Skip to content

Commit

Permalink
Merge pull request #44 from dreamit-de/43-timeout-function
Browse files Browse the repository at this point in the history
#43 Add TimeoutFunction
  • Loading branch information
sgohlke authored Aug 9, 2024
2 parents 4044a5d + a1c84a2 commit 6df1248
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 4 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# funpara

Function parameter library to ease development and testing. The library provides Date, Exit and Fetch related functions that can be used without complicated spy/mock setups so that an application can easily be tested with function parameters.
Function parameter library to ease development and testing. The library provides Date, Exit, Fetch and Timeout related functions that can be used without complicated spy/mock setups so that an application can easily be tested with function parameters.

## Installation

Expand Down Expand Up @@ -63,6 +63,7 @@ In **tests/index.test.ts** there are additional examples how the available code
- **DateFunction**: Type for a function that returns a Date.
- **ExitFunction**: Type for a function that given an exit code does not return anything.
- **FetchFunction**: Type for a fetch function that given an input (url, request, etc.) and request init returns a Promise<Response>
- **TimeoutFunction**: Type for a function that given a TimerHandler, optional timeout and arguments returns the timeout ID as number.

### Core functions

Expand All @@ -82,6 +83,7 @@ The following functions return a fix value. This can be helpful for testing code
- **brokenJSONFetchFunction**: FetchFunction that returns a fixed Response with broken JSON (missing bracket)
- **unknownContentTypeFetchFunction**: FetchFunction that returns a fixed Response with an unknown Content-Type ('application/unknown')
- **timeoutFetchFunction**: FetchFunction that returns a fixed Response that throws a Timeout error.
- **noCallbackTimeoutFunction**: TimeoutFunction that does not call the callback function but returns a fixed timeout ID 1.

## Contact

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@dreamit/funpara",
"version": "1.1.0",
"version": "1.2.0",
"description": "Function parameter library for coding and testing",
"scripts": {
"build": "tsup-node",
Expand Down
23 changes: 23 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,26 @@ export type ExitFunction = (code: number) => never
export const doNotExitFunction: ExitFunction = (code: number): never => {
throw new Error(`Exit function was called with code ${code}`)
}

// Timeout function related types and functions

/**
* Type for a function that given a TimerHandler, optional timeout and arguments returns the timeout ID as number.
* @param {TimerHandler} handler The TimerHandler to be called (i.e. in most cases a callback function)
* @param {number} timeout The timeout in milliseconds
* @param {any[]} timeoutArguments The arguments to be passed to the handler
* @returns {number} The timeout ID as number
*/
export type TimeoutFunction = (
handler: TimerHandler,
timeout?: number,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
...timeoutArguments: any[]
) => number

/**
* TimeoutFunction that does not call the callback function but returns a fixed timeout ID 1.
* Can be used in testing to avoid the tests waiting for the timeout to finish.
* @returns {number} Fixed timeout ID 1
*/
export const noCallbackTimeoutFunction: TimeoutFunction = (): number => 1
41 changes: 39 additions & 2 deletions tests/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import type { DateFunction, FetchFunction } from '@/index'
import type {
DateFunction,
ExitFunction,
FetchFunction,
TimeoutFunction,
} from '@/index'
import {
brokenJSONFetchFunction,
doNotExitFunction,
fixedDateFunction,
fixedResponseFetchFunction,
noCallbackTimeoutFunction,
notFoundFetchFunction,
nowDateFunction,
testDateFunction,
Expand All @@ -19,12 +25,16 @@ import { expect, test } from 'vitest'
* and prepareLogMessage functions in order to be able to set a custom DateFunction if necessary.
*/
class Logger {
logEntries: Array<string> = []

/**
* Setting the default value to nowDateFunction will make it
* easier to call the function without the caller providing a DateFunction argument
*/
log(message: string, dateFunction: DateFunction = nowDateFunction()): void {
console.log(this.prepareLogMessage(message, dateFunction))
const logEntry = this.prepareLogMessage(message, dateFunction)
this.logEntries.push(logEntry)
console.log(logEntry)
}

/**
Expand Down Expand Up @@ -167,3 +177,30 @@ test('Test exit functions', () => {
'Exit function was called with code 1',
)
})

test('Test timeout functions', () => {
const logger = new Logger()
// noCallbackTimeoutFunction should return a fixed timeout ID 1
expect(
noCallbackTimeoutFunction(
() => logger.log('This should not be executed!'),
1000,
),
).toBe(1)
// Log call in callback function should not be executed
expect(logger.logEntries.length).toBe(0)
})

test('Test types match expected types of their default/original implementation', () => {
/*
* Note:
* While this test might still pass for type mismatches,
* the type check in "check" script will fail if the types do not match and cannot be casted
*/
const defaultFetchFunction: FetchFunction = global.fetch
expect(defaultFetchFunction).toBeDefined()
const defaultExitFunction: ExitFunction = process.exit
expect(defaultExitFunction).toBeDefined()
const defaultTimeoutFunction: TimeoutFunction = global.setTimeout
expect(defaultTimeoutFunction).toBeDefined()
})

0 comments on commit 6df1248

Please sign in to comment.