Skip to content

Commit

Permalink
Fix #321: improve ResponseHandler types
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mrijke committed Jun 7, 2021
1 parent ddca216 commit ad10b86
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
5 changes: 4 additions & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,11 @@ export type ResponseHandler = {
(request: FakeXMLHttpRequest & ExtraRequestData):
| ResponseData
| PromiseLike<ResponseData>;
};

export type ResponseHandlerInstance = ResponseHandler & {
async: boolean;
numberOfCalls: number;
};
}

export default Server;
16 changes: 9 additions & 7 deletions src/pretender.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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 ' +
Expand All @@ -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;
Expand Down

0 comments on commit ad10b86

Please sign in to comment.