ctimmerm / axios-mock-adapter

Axios adapter that allows to easily mock requests
MIT License
3.47k stars 245 forks source link

Allow using route params #205

Open kierate opened 5 years ago

kierate commented 5 years ago

Working with route params is more convenient than defining the regex in the matcher itself (avoids duplication of regexes for similar routes, allows using the same routes you have on the backend or in the API spec etc.)

This implementation:

Example using the colon notation:

const routeParams = {
  ':userId': '[0-9]{1,8}',
  ':filter': 'active|inactive|all',
}
const mock = new MockAdapter(axios, {}, routeParams);

mock.onGet('/users/:userId/posts/:filter').reply(function(config) {
  const { userId, filter } = config.routeParams;

  // userId === '123'
  // filter === 'active'

  return [200, {}];
});

axios.get('/users/123/posts/active');

Example using the curly braces notation:

const routeParams = {
  '{uuid}': '[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}',
  '{page}': '\\d?',
}
const mock = new MockAdapter(axios, {}, routeParams);

mock.onGet('/users/{uuid}/posts/{page}').reply(function(config) {
  const { uuid, page } = config.routeParams;

  // uuid === 'b67c0749-656c-4beb-9cd9-17e274a648d9'
  // page === '3'

  return [200, {}];
});

axios.get('/users/b67c0749-656c-4beb-9cd9-17e274a648d9/posts/3');

This addresses requests from https://github.com/ctimmerm/axios-mock-adapter/issues/199 and https://github.com/ctimmerm/axios-mock-adapter/issues/82

hernanif1 commented 5 years ago

great solution, what happened?

bahung1221 commented 4 years ago

This is great feature, what happened which this pull request? Thanks you so much 😄

yss14 commented 4 years ago

Has this PR been rejected silently?

11joselu commented 4 years ago

Any news?

grbspltt commented 4 years ago

Can this please be merged?

dschreij commented 4 years ago

I was looking for something exactly like this. There don't appear to be any showstoppers here from merging this, right?

thany commented 3 years ago

This should be merged. Keeping a PR open for this long is never a good Idea. Reject or (resolve conflicts and) merge, but please don't ignore, dear Axios authors.

hernanif1 commented 3 years ago

@ctimmerm ?

Tofandel commented 3 years ago

Such a needed and requested feature :disappointed:

dguay commented 3 years ago

Still not merged after 2 years?

thany commented 3 years ago

It's possible that this project is dead, but only @ctimmerm knows, and @ctimmerm doesn't say 🤨

bertho-zero commented 3 years ago

https://github.com/pillarjs/path-to-regexp could be embed, it's used in express and react-router

bertho-zero commented 3 years ago

I used a different approach which doesn't require a 3rd argument in https://github.com/ctimmerm/axios-mock-adapter/pull/316/files.