From ad10b863bb0c3111f2129f85cf4d0c45ed752575 Mon Sep 17 00:00:00 2001 From: Maarten Rijke Date: Mon, 7 Jun 2021 15:58:54 +0200 Subject: [PATCH 1/2] Fix #321: improve ResponseHandler types Fix the ResponseHandler type by introducing a new type that extends the ResponseHandler and adds the instance-specific attributes to it (async and numberOfCalls). This will allow TS clients to use the API as described in the README. --- index.d.ts | 5 ++++- src/pretender.ts | 16 +++++++++------- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/index.d.ts b/index.d.ts index 153a2fe..d19baa3 100644 --- a/index.d.ts +++ b/index.d.ts @@ -47,8 +47,11 @@ export type ResponseHandler = { (request: FakeXMLHttpRequest & ExtraRequestData): | ResponseData | PromiseLike; +}; + +export type ResponseHandlerInstance = ResponseHandler & { async: boolean; numberOfCalls: number; -}; +} export default Server; diff --git a/src/pretender.ts b/src/pretender.ts index 0795e33..36f12f9 100644 --- a/src/pretender.ts +++ b/src/pretender.ts @@ -1,7 +1,7 @@ import * as FakeFetch from 'whatwg-fetch'; import FakeXMLHttpRequest from 'fake-xml-http-request'; import { Params, QueryParams } from 'route-recognizer'; -import { ResponseHandler } from '../index.d'; +import { ResponseHandler, ResponseHandlerInstance } from '../index.d'; import Hosts from './hosts'; import parseURL from './parse-url'; import Registry from './registry'; @@ -143,7 +143,7 @@ export default class Pretender { url: string, handler: ResponseHandler, async: boolean - ): ResponseHandler { + ): ResponseHandlerInstance { if (!handler) { throw new Error( 'The function you tried passing to Pretender to handle ' + @@ -154,20 +154,22 @@ export default class Pretender { ); } - handler.numberOfCalls = 0; - handler.async = async; - this.handlers.push(handler); + const handlerInstance = handler as ResponseHandlerInstance; + + handlerInstance.numberOfCalls = 0; + handlerInstance.async = async; + this.handlers.push(handlerInstance); let registry = this.hosts.forURL(url)[verb]; registry.add([ { path: parseURL(url).fullpath, - handler: handler, + handler: handlerInstance, }, ]); - return handler; + return handlerInstance; } passthrough = PASSTHROUGH; From 88f5ec16144a9d3f5421ed191e871c1dfa6ac3c4 Mon Sep 17 00:00:00 2001 From: Maarten Rijke Date: Mon, 7 Jun 2021 16:07:42 +0200 Subject: [PATCH 2/2] make the RequestHandler return the ResponseHandlerInstance properly --- index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.d.ts b/index.d.ts index d19baa3..7e17ae3 100644 --- a/index.d.ts +++ b/index.d.ts @@ -36,7 +36,7 @@ export type RequestHandler = ( urlExpression: string, response: ResponseHandler, asyncOrDelay?: boolean | number -) => void; +) => ResponseHandlerInstance; export type ResponseData = [number, { [k: string]: string }, string]; interface ExtraRequestData {