pretenderjs / pretender

A mock server library with a nice routing DSL
MIT License
1.26k stars 158 forks source link

Types for RequestHandler are too strict #321

Closed mrijke closed 3 years ago

mrijke commented 3 years ago

With the rewrite to TypeScript, the API as described in the README does not work in TypeScript projects. The following:

const server = new Pretender(function() {
  this.put('/api/songs/99', request => [404, {}, ""]);
});

fails with the following TS error:

Argument of type '(request: FakeXMLHttpRequest & ExtraRequestData) => [number, {}, string]' is not assignable to parameter of type 'ResponseHandler'.
  Type '(request: FakeXMLHttpRequest & ExtraRequestData) => [number, {}, string]' is missing the following properties from type 'ResponseHandler': async, numberOfCallsts(2345)

The extra attributes that were introduced on the handler instance (async and numberOfCalls) are also mandatory to provide when defining the mock itself - which I think is not intended, these are meant to be (readonly) properties, correct?

For now the following workaround seems to make TS happy - but it's not very ideal:

const handler = (): ResponseData => [
  200,
  { "Content-Type": "applicatoin/json" },
  JSON.stringify({ status: "OK!" }),
];
handler.async = false;
handler.numberOfCalls = 0;