sanity-io/get-it

Add support for mocking responses

rexxars opened this issue · 1 comments

With the middleware architecture in place, it shouldn't be too difficult to add support for mocking responses. That would be a nice addition that would ease testing in a lot of scenarios, in a way that would work in both browsers and on the server.

Just released 2.1.0 which includes the low-level primitive middleware injectResponse for doing this. It can also be used to create a cache, for instance. I suspect I will create a higher-order (separate) module to utilize it more easily in terms of automatically removing matched requests, sort of like what nock does.

You can't currently asynchronously resolve a response, but this is something that I want to add in the future.

Basic usage:

const getIt = require('get-it')
const {injectResponse, promise} = require('get-it/middleware')

const inject = evt => {
  const url = evt.context.options.url
  if (url.includes('/some-thing')) {
    return {body: 'Yay, some thing!'}
  }

  // Otherwise, use unmocked behaviour
}

const request = getIt([
  promise(),
  injectResponse({inject})
])

request('http://some.url/foo') // Unmocked, standard behaviour
request('http://some.url/some-thing') // Mocked, will emit response on next tick