Skip to content

Commit

Permalink
Merge remote-tracking branch 'upstream/master'
Browse files Browse the repository at this point in the history
  • Loading branch information
akkadaska committed Jul 29, 2023
2 parents bdfd521 + d84a304 commit 9fe5c01
Show file tree
Hide file tree
Showing 16 changed files with 4,228 additions and 2,862 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ Mostly, there's no playground to modify the response and see the changes in the

### Documentation

[See the documentation](https://storybook-addon-mock.vercel.app)
[See the documentation](https://storybook-addon-mock.netlify.app)

[Older(2.*) version documentation](https://github.com/nutboltu/storybook-addon-mock/blob/2.4.1/README.md)
### License
Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@
"scripts": {
"clean": "rm -rf dist",
"build": "yarn workspaces run build",
"storybook": "yarn workspace storybook-addon-mock-docs run storybook",
"lint": "yarn workspaces run lint",
"lint:fix": "yarn workspaces run lint:fix",
"test": "yarn workspaces run test",
"ci": "yarn run lint && yarn run test && yarn run build-addon && yarn run build-storybook",
"ci": "yarn run lint && yarn run test && yarn run build-addon && yarn run docs:build",
"build-addon": "yarn workspace storybook-addon-mock run build",
"build-storybook": "yarn workspace storybook-addon-mock-docs run build",
"docs:start": "yarn workspace storybook-addon-mock-docs run storybook",
"docs:build": "yarn workspace storybook-addon-mock-docs run build",
"dedup": "yarn-deduplicate"
},
"repository": {
Expand Down
13 changes: 12 additions & 1 deletion packages/mock-addon-docs/.storybook/main.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
import remarkGfm from 'remark-gfm';

export default {
stories: [
'../stories/**/*stories.mdx',
'../stories/**/*stories.@(js|jsx|ts|tsx)',
],
addons: [
'@storybook/addon-links',
'@storybook/addon-docs',
{
name: '@storybook/addon-docs',
options: {
mdxPluginOptions: {
mdxCompileOptions: {
remarkPlugins: [remarkGfm],
},
},
},
},
'@storybook/addon-viewport',
'@storybook/addon-toolbars',
'../../mock-addon/preset.js',
Expand Down
19 changes: 10 additions & 9 deletions packages/mock-addon-docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,20 @@
"author": "Farhad Yasir(nutboltu)",
"license": "MIT",
"devDependencies": {
"@storybook/addon-actions": "^7.0.0",
"@storybook/addon-essentials": "^7.0.0",
"@storybook/addon-interactions": "^7.0.0",
"@storybook/addon-links": "^7.0.0",
"@storybook/addon-actions": "^7.0.26",
"@storybook/addon-essentials": "^7.0.26",
"@storybook/addon-interactions": "^7.0.26",
"@storybook/addon-links": "^7.0.26",
"@storybook/react-webpack5": "^7.0.26",
"@storybook/storybook-deployer": "^2.8.16",
"@storybook/react-webpack5": "^7.0.0",
"storybook": "^7.0.0"
"storybook": "^7.0.26"
},
"dependencies": {
"axios": "^1.3.4",
"superagent": "^8.0.9",
"react": "^18.2.0",
"react-code-blocks": "0.0.9-0",
"react-dom": "^18.2.0"
"react-dom": "^18.2.0",
"remark-gfm": "^3.0.1",
"superagent": "^8.0.9"
}
}
}
2 changes: 1 addition & 1 deletion packages/mock-addon-docs/stories/docs/footer/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export const Footer = ({ title, subtitle, actionText, actionLink }) => (
<strong>{title}</strong>
{subtitle}
</div>
<LinkTo className="continue" kind={actionLink} story="page">
<LinkTo className="continue" kind={actionLink} story="docs">
{actionText}
</LinkTo>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ See the <LinkTo kind="Docs/Advanced Setup" story="page">Advanced Setup</LinkTo>

<h3 className="subheading">3. Configure mock data</h3>

Add your mock data in the story parameters. This `mockData` attirbutes is an <strong>array</strong> of mock object.
Add your mock data in the story parameters. This `mockData` attribute is an <strong>array</strong> of the mock object.

```js
import React from 'react';
Expand Down Expand Up @@ -77,7 +77,8 @@ const Template = () => <FetchExample />;
export const FetchCall = Template.bind({});

```
Each mock object contains the following properties.

Each mock object contains the following properties.

| Property | Description | Required | Default |
| ---------- | :------------------------------------------------------------------------------------------ | :------- | :------ |
Expand Down
2 changes: 1 addition & 1 deletion packages/mock-addon/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ Mostly, there's no playground to modify the response and see the changes in the

### Documentation

[See the documentation](https://storybook-addon-mock.vercel.app)
[See the documentation](https://storybook-addon-mock.netlify.app)

[Older(2.*) version documentation](https://github.com/nutboltu/storybook-addon-mock/blob/2.4.1/README.md)
### License
Expand Down
2 changes: 1 addition & 1 deletion packages/mock-addon/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "storybook-addon-mock",
"version": "4.0.0",
"version": "4.1.0",
"description": "A storybook addon to mock fetch/XHR request",
"keywords": [
"storybook",
Expand Down
14 changes: 8 additions & 6 deletions packages/mock-addon/src/utils/array.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
export function arrayEquals(a, b) {
return (
Array.isArray(a) &&
Array.isArray(b) &&
a.length === b.length &&
a.every((val, index) => val === b[index])
);
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) {
return false;
}

const sortedA = a.slice().sort();
const sortedB = b.slice().sort();

return !sortedA.some((val, index) => val !== sortedB[index]);
}
27 changes: 27 additions & 0 deletions packages/mock-addon/src/utils/array.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { arrayEquals } from './array';

describe('array', () => {
describe('arrayEquals', () => {
it('should match two arrays based on values, ignoring order', () => {
const array1 = ['jeff', 'fred', 'cecily'];
const array2 = ['fred', 'cecily', 'jeff'];

const result = arrayEquals(array1, array2);

expect(result).toBeTruthy();
});

it('should not mutate the original arrays', () => {
const array1 = ['jeff', 'fred', 'cecily'];
const array2 = ['fred', 'cecily', 'jeff'];

const array1String = array1.toString();
const array2String = array2.toString();

arrayEquals(array1, array2);

expect(array1.toString()).toBe(array1String);
expect(array2.toString()).toBe(array2String);
});
});
});
105 changes: 77 additions & 28 deletions packages/mock-addon/src/utils/faker.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,20 +117,40 @@ export class Faker {
const { url, method } = request;
const matched = this.matchMock(url, method);

if (matched) {
const { response, status, delay = 0 } = matched;
return new Promise((resolve) => {
setTimeout(() => {
if (typeof response === 'function') {
resolve(new Response(url, status, response(request)));
} else {
resolve(new Response(url, status, response));
}
}, +delay);
});
if (!matched) {
// eslint-disable-next-line no-restricted-globals
return global.realFetch(input, options);
}
// eslint-disable-next-line no-restricted-globals
return global.realFetch(input, options);

const { response, status, delay = 0 } = matched;

let mockResponseSent = false;

return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
if (typeof response === 'function') {
resolve(new Response(url, status, response(request)));
} else {
resolve(new Response(url, status, response));
}

mockResponseSent = true;
}, +delay);

request.signal?.addEventListener('abort', () => {
if (mockResponseSent) {
return;
}

timeoutId && clearTimeout(timeoutId);

const error = new Error(request.signal.reason);

error.name = 'AbortError';

reject(error);
});
});
};

mockXhrRequest = (request) => {
Expand All @@ -155,37 +175,66 @@ export class Faker {
}
}, +delay);
} else {
// eslint-disable-next-line new-cap
const realXhr = new global.realXMLHttpRequest();
const RealXMLHTTPRequest = global.realXMLHttpRequest;
const realXhr = new RealXMLHTTPRequest();
const fakeXhr = request._responseReceiver;

realXhr.open(method, url);

realXhr.timeout = fakeXhr.timeout;
realXhr.withCredentials = fakeXhr.withCredentials;
this.transferEventListeners(fakeXhr, realXhr);
setRequestHeaders(
realXhr,
new Map(Object.entries(request.requestHeaders.getHash()))
);
realXhr.withCredentials = request.withCredentials;

realXhr.onreadystatechange = function onReadyStateChange() {
if (realXhr.readyState === 4 && realXhr.status === 200) {
realXhr.addEventListener('readystatechange', () => {
if (realXhr.readyState === XMLHttpRequest.DONE) {
request.respond(
200,
realXhr.status,
getResponseHeaderMap(realXhr),
realXhr.responseText
realXhr.responseText,
realXhr.statusText
);
}
};

realXhr.send(body);
});

const errorHandler = function () {
return 'Network failed';
};
realXhr.addEventListener('abort', () => request.abort());
realXhr.addEventListener('error', () => request.setNetworkError());
realXhr.addEventListener('timeout', () =>
request.setRequestTimeout()
);

realXhr.onerror = errorHandler;
realXhr.ontimeout = errorHandler;
realXhr.send(body);
}
};

transferEventListeners(fakeXhr, realXhr) {
fakeXhr._listeners.forEach((handlers, eventName) => {
if (eventName === 'loadstart') {
// We can't transfer loadstart because it fires as soon as the user calls xhr.start() and
// before this method is called, so to avoid calling it twice, we refrain from transferring it.
return;
}

handlers.forEach(
({ isEventHandlerProperty, listener, useCapture, once }) => {
if (isEventHandlerProperty) {
realXhr[`on${eventName}`] = listener;
} else {
realXhr.addEventListener(eventName, listener, {
once,
capture: useCapture,
});
}
}
);
});

fakeXhr._listeners.clear();
}

restore = () => {
this.requestMap = {};
};
Expand Down
Loading

0 comments on commit 9fe5c01

Please sign in to comment.