ctimmerm / axios-mock-adapter

Axios adapter that allows to easily mock requests
MIT License
3.44k stars 244 forks source link

Support for params serializer #120

Open Kocal opened 6 years ago

Kocal commented 6 years ago

Hey, first let my thank you for this amazing library, you made axios soooo easy to mock and test! :smile:


Today I encountered a problem when I was trying to mock axios requests which should use a params serializer.

I'm requesting the new Twitch API and request parameters are now &-repeated (source). That means I should request https://api.twitch.tv/helix/games?user_id=123&user_id=456 instead of https://api.twitch.tv/helix/games?user_id=123,456.

Here is my code which request the Twitch API:

const qs = require('qs'); // https://github.com/ljharb/qs

const url = 'https://api.twitch.tv/helix/streams';
const config = {
  params: {
    user_id: [123, 456],
  },
  paramsSerializer(params) {
    return qs.stringify(params, { arrayFormat: 'repeat' });
  }
}

axios
  .get(url, config)
  .then() // ...

And here is my code which should test my request:

// skip imports

const url = 'https://api.twitch.tv/helix/streams';
const config = {
  params: {
    user_id: [123, 456],
  },
  // no `paramsSerializer` because it is not supported
};

axiosMock
  .onGet(url, config)
  .replyOnce(200, {
    // ...
  });

testMyRequest();

And so, since params are serialized as ?user_id=123&user_id=456 the mock is not working.

tconroy commented 5 years ago

+1, running into the same issue. Did you manage to find a workaround, @Kocal?

Kocal commented 5 years ago

Yes, the workaround is here https://github.com/ctimmerm/axios-mock-adapter/pull/121 :stuck_out_tongue_closed_eyes:

I will rebase the PR