api icon indicating copy to clipboard operation
api copied to clipboard

Allow for the easy creation of mocking requests

Open erunion opened this issue 4 years ago • 1 comments

When working with an API, it's helpful to be able to mock out requests when unit testing client functionality. Since we've got the OpenAPI definition on hand for the API in question, we know everything about the API and should be able to accept and return mock data according to the contract.

Nock, the library that we'd likely use for supporting mocks, has an environmental flag that lets you completely disable Nock.

Along these lines, the two ideas that we have for mocking API requests out of SDKs are:

  • Expose an API_MOCKS=true environmental variable that when enabled, causes the SDK to disable network traffic and mock out all requests.
  • Alternatively, if you just want to mock out a single endpoint we should have a .mock() method that you could chain to your API call as such:
const sdk = require('api')('petstore.json');
sdk.mock().listPets().then(res => {
  // `res` is a 200 response and `res.json()` contains mock data based on the API
});

Unanswered questions right now are:

  • How would we mock out failing requests? Would that entail you supplying .mock() with the status code you wish to cause .listPets() to return?

erunion avatar May 21 '20 16:05 erunion

I like the environment variable approach, then your code can stay the same and you dont have to add anything for your test environment.

If we don't like the all or nothing boolean approach of doing API_MOCKS=true you could also possible expand that to single endpoints API_MOCKS=listPets,getPets and have others not be mocked at that point. I think it's too early to say whether this would be useful at this point though.

domharrington avatar May 21 '20 17:05 domharrington