axios-mock-adapter
axios-mock-adapter copied to clipboard
Allow using route params
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:
- allows configuring a set of known route params as the 3rd argument to the constructor
- exposes the values for the params on matched routes under
config.routeParams
- allows using both colon (
:userId
) and curly braces ({userId}
) for route params
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
great solution, what happened?
This is great feature, what happened which this pull request? Thanks you so much 😄
Has this PR been rejected silently?
Any news?
Can this please be merged?
I was looking for something exactly like this. There don't appear to be any showstoppers here from merging this, right?
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.
@ctimmerm ?
Such a needed and requested feature :disappointed:
Still not merged after 2 years?
It's possible that this project is dead, but only @ctimmerm knows, and @ctimmerm doesn't say 🤨
https://github.com/pillarjs/path-to-regexp could be embed, it's used in express and react-router
I used a different approach which doesn't require a 3rd argument in https://github.com/ctimmerm/axios-mock-adapter/pull/316/files.