axios-mock-adapter icon indicating copy to clipboard operation
axios-mock-adapter copied to clipboard

return handler in reply(...) mocks in order to allow removing handler and monitoring calls

Open burgalon opened this issue 6 years ago • 5 comments

Similarly to WebMock it would be nice if mocking replies will return the handler so that later we can:

  1. Assert that mock has been called
  2. Remove handler if necessary

burgalon avatar Aug 21 '18 08:08 burgalon

Thanks for your pull request! I agree that this would be a useful feature, but if the handler is returned from reply it would mean quite a large breaking change is introduced (any existing code that uses chaining would no longer work). Maybe it could instead be done in a way that is backwards compatible by adding an extra method? Something like:

var handler = mock.onGet(...).reply(...).handler();

ctimmerm avatar Aug 23 '18 19:08 ctimmerm

Hey Colin, The suggestion .handler() doesn't seem quite right: That would mean that we we would need to save the last handler in _this and then .handler() would return it? More generally, I think it would be nice if we take axios-mock-adapter further in the direction of not jus mocking, but also allowing matchers and assertions for requests which have occured like WebMock. Thus I think letting go of chaining, is for a good cause :)

burgalon avatar Aug 26 '18 07:08 burgalon

What if we could have the best of both worlds and instead of returning either the instance or the handler, return a proxy that proxies the methods/properties to either the instance or the handler.

A contrived example:

function createProxy(instance, handler) {
  var proxy = {
    handler: handler,
    instance: instance,

    get: function() {
      return instance.get.apply(instance, arguments);
    }
  };

  Object.defineProperty(proxy, 'called', {
    get: function() {
      return handler.called;
    },

    set: function(value) {
      handler.called = value;
    }
  });

  return proxy;
}

ctimmerm avatar Aug 26 '18 09:08 ctimmerm

personally I like when things are straight forward, and the object type at hand is of clear type and interface. The suggested proxy makes it harder to follow the code and understand

burgalon avatar Aug 26 '18 10:08 burgalon

we could have a flag at the mock level determining what's the returned object... but that will create communities forking usage instead of forked code :)

burgalon avatar Aug 26 '18 11:08 burgalon