Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: ignore URL params on matching #115

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ There are few packages those help the developers to mock the backend requests wh

| Property | Description | Required | Default |
| ---------- | :------------------------------------------------------------------------------------------ | :------- | :------ |
| `url` | Supports both **named parameters** (`/:foo/:bar`) and **query parameters**.(`/foo?bar=true`) | Y | - |
| `url` | Supports both **named parameters** (`/:foo/:bar`) and **query parameters** (`/foo?bar=true`) in [path-to-regexp](https://github.com/pillarjs/path-to-regexp/blob/master/Readme.md) format. | Y | - |
| `method` | Supports `GET`, `POST`, `PUT`, `PATCH` and `DELETE` methods. | - | `GET` |
| `status` | All possible HTTP status codes. | - | `200` |
| `response` | JSON format or function. <br/> <br/> Response function is a function that contains request object as a parameter. See the **Custom Response** section for example. | Y | - |
Expand Down Expand Up @@ -155,7 +155,7 @@ Default.parameters = {
if (searchParams.id == 1) {
return {
data: 'Custom data for id 1',
};
};
} else if (body.name === 'mock') {
return {
data: 'Custom data for name mock',
Expand Down
20 changes: 19 additions & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,21 @@
declare const withMock: (storyFn: any) => any;
declare const withMock: (options: RequestInfo[]) => any;
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And also by the way I wrote base types for TypeScript, if you don't mind.


export default withMock;

export interface RequestInfo {
url: string;
response: object | ((request: ResponseRequestParam) => object);
/** @default GET */
method?: string;
/** @default 200 */
status?: number;
/** @default 0 */
delay?: number;
}

export interface ResponseRequestParam {
method: string;
url: url;
body: RequestInit['body'];
searchParams?: Record<string, string>;
}
4 changes: 2 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ export default makeDecorator({
parameterName: 'mockData',
// This means don't run this decorator if the notes decorator is not set
skipIfNoParametersOrOptions: true,
wrapper: (getStory, context, { parameters }) => {
wrapper: (getStory, context, { options = [], parameters = [] }) => {
const channel = addons.getChannel();
faker.makeInitialRequestMap(parameters);
faker.makeInitialRequestMap(options.concat(parameters));
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At the same time I supported story options.


// Our simple API above simply sets the notes parameter to a string,
// which we send to the channel
Expand Down
8 changes: 0 additions & 8 deletions src/utils/array.js

This file was deleted.

21 changes: 8 additions & 13 deletions src/utils/faker.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
getResponseHeaderMap,
defaultResponseHeaders,
} from './headers';
import { arrayEquals } from './array';
import { getNormalizedUrl } from './url';

let global =
Expand All @@ -34,9 +33,9 @@ export class Faker {

getRequests = () => Object.values(this.requestMap);

getKey = (url = '', searchParamKeys = [], method = 'GET') =>
getKey = (url = '', method = 'GET') =>
url && method
? [url, ...searchParamKeys, method.toLowerCase()].join('_')
? [url, method.toLowerCase()].join('_')
: '';

makeInitialRequestMap = (requests) => {
Expand All @@ -51,12 +50,9 @@ export class Faker {
};

add = (request) => {
const { path, searchParamKeys } = getNormalizedUrl(request.url);
const key = this.getKey(path, searchParamKeys, request.method);
const key = this.getKey(request.url, request.method);
this.requestMap[key] = {
...request,
path,
searchParamKeys,
method: request.method || 'GET',
status: request.status || 200,
delay: request.delay || 0,
Expand All @@ -66,8 +62,7 @@ export class Faker {

update = (item, fieldKey, value) => {
const { url, method } = item;
const { path, searchParamKeys } = getNormalizedUrl(url);
const itemKey = this.getKey(path, searchParamKeys, method);
const itemKey = this.getKey(url, method);

if (
// eslint-disable-next-line no-prototype-builtins
Expand All @@ -80,17 +75,17 @@ export class Faker {
};

matchMock = (url, method = 'GET') => {
const { path, searchParamKeys } = getNormalizedUrl(url);
const { fullUrl } = getNormalizedUrl(url);

for (let key in this.requestMap) {
const { url: requestUrl, method: requestMethod } =
this.requestMap[key];
const { path: requestPath, searchParamKeys: requestSearchKeys } =
const { fullUrlEscaped } =
getNormalizedUrl(requestUrl);

if (
match(requestPath)(path) &&
match(fullUrlEscaped)(fullUrl) &&
method == requestMethod &&
arrayEquals(searchParamKeys, requestSearchKeys) &&
!this.requestMap[key].skip
) {
return this.requestMap[key];
Expand Down
21 changes: 15 additions & 6 deletions src/utils/faker.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,10 @@ describe('Faker', () => {
const actual = faker.getKey('', [], '');
expect(actual).toEqual('');
});
it('should return a string binding url and method with underscore if searchParamKeys is empty', () => {
const actual = faker.getKey('google.com', [], 'GET');
it('should return a string binding url and method with underscore', () => {
const actual = faker.getKey('google.com', 'GET');
expect(actual).toEqual('google.com_get');
});
it('should return a string binding url, search params keys, and method with underscore', () => {
const actual = faker.getKey('google.com', ['all', 'only'], 'GET');
expect(actual).toEqual('google.com_all_only_get');
});
});
describe('makeInitialRequestMap', () => {
const faker = new Faker();
Expand Down Expand Up @@ -69,6 +65,13 @@ describe('Faker', () => {
response: {},
delay: 0,
},
{
url: 'http://request.com?a=1&b=2',
method: 'GET',
status: 200,
response: {},
delay: 0,
},
];
faker.makeInitialRequestMap(requests);

Expand All @@ -88,6 +91,12 @@ describe('Faker', () => {
expect(actual.method).toEqual(requests[2].method);
expect(actual.skip).toEqual(false);
});
it('should return request if url matches with the query parameters', () => {
const actual = faker.matchMock('http://request.com?a=1&b=2', 'GET');
expect(actual.url).toEqual(requests[3].url);
expect(actual.method).toEqual(requests[3].method);
expect(actual.skip).toEqual(false);
});
});

describe('restore', () => {
Expand Down
5 changes: 5 additions & 0 deletions src/utils/url.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,13 @@ export const getNormalizedUrl = (rawUrl = '') => {
searchParamKeys.push(key);
}
}

const searchEscaped = url.search ? '\\' + url.search : '';

return {
path: url.host + url.pathname,
searchParamKeys,
fullUrl: url.host + url.pathname + url.search,
fullUrlEscaped: url.host + url.pathname + searchEscaped,
};
};