Skip to content
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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ There are few packages those help the developers to mock the backend requests wh
| `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 | - |
| `delay` | Emulate delayed response time in milliseconds. | - | `0` |
| `uploadFrameCount` | Emulate response progress, progress will be emitted in delayed time duration. | - | `5` |
| `uploadTimingFunction` | Emulate response progress, the timing function makes customized progress. Supports `linear`, `ease-in`, `ease-out`. | - | `linear` |

> You can change the **status**, **response** and **delay** from the storybook panel on the fly! :rocket:

Expand Down
53 changes: 52 additions & 1 deletion src/utils/faker.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,11 +121,38 @@ export class Faker {
return global.realFetch(input, options);
};

/**
* mock xhr request
* @param {import('mock-xmlhttprequest').MockXhr} xhr
*/
mockXhrRequest = (xhr) => {
const { method, url, body } = xhr;
const matched = this.matchMock(url, method);
if (matched) {
const { response, status, delay = 0 } = matched;
const {
response,
status,
delay = 0,
uploadTimingFunction = 'linear',
uploadFrameCount = 5,
} = matched;
// split delays
let timeForTransitionEmit = [];
if (delay > 0) {
timeForTransitionEmit = getTimingSlice(
uploadTimingFunction,
uploadFrameCount
);
}

timeForTransitionEmit.forEach((progressRatio, timeoutIndex) => {
setTimeout(() => {
xhr.uploadProgress(
progressRatio * xhr.getRequestBodySize()
);
}, ((timeoutIndex + 1) * +delay) / uploadFrameCount);
});

setTimeout(() => {
if (typeof response === 'function') {
const data = response(new Request(url, { method, body }));
Expand Down Expand Up @@ -172,4 +199,28 @@ export class Faker {
};
}

function getTimingSlice(timingFunction, sliceCount) {
const timeSlice = [];

if (timingFunction === 'ease-in') {
for (let i = 0; i < sliceCount; i++) {
timeSlice.splice(i, 0, Math.pow((i + 1) / sliceCount, 1.675));
}
} else if (timingFunction === 'ease-out') {
for (let i = 0; i < sliceCount; i++) {
timeSlice.splice(
i,
0,
1 - Math.pow(1 - (i + 1) / sliceCount, 1.675)
);
}
} else {
// linear
for (let i = 0; i < sliceCount; i++) {
timeSlice.splice(i, 0, (i + 1) / sliceCount);
}
}
return timeSlice;
}

export default new Faker();
10 changes: 9 additions & 1 deletion stories/components/non-get-request/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export const NonGetRequest = ({ title, method, callApi }) => {
const [todoName, setTodoName] = useState('Item 1');
const [response, setResponse] = useState({});
const [loading, setLoading] = useState(false);
const [uploadProgress, setUploadProgress] = useState(0);

const handleSubmit = async (event) => {
event.preventDefault();
Expand All @@ -27,6 +28,9 @@ export const NonGetRequest = ({ title, method, callApi }) => {
url,
method,
body: { name: todoName },
onUploadProgress: (pev) => {
setUploadProgress(pev.loaded / pev.total);
},
});
setResponse(apiResponse);
setLoading(false);
Expand Down Expand Up @@ -62,7 +66,11 @@ export const NonGetRequest = ({ title, method, callApi }) => {
)}
<input type="submit" value="Submit" style={buttonStyles} />
</form>
<ResponseContainer loading={loading} {...response} />
<ResponseContainer
uploadProgress={uploadProgress}
loading={loading}
{...response}
/>
</StoryContainer>
);
};
Expand Down
14 changes: 12 additions & 2 deletions stories/components/response-container/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,19 @@ import PropTypes from 'prop-types';

import { errorContainerStyles, responseContainerStyles } from './styles';

export const ResponseContainer = ({ loading, status, error, data }) => (
export const ResponseContainer = ({
loading,
uploadProgress,
status,
error,
data,
}) => (
<>
{loading ? (
<div style={responseContainerStyles}>Loading...</div>
<div style={responseContainerStyles}>
Loading...
{!!uploadProgress && <span>{uploadProgress * 100} %</span>}
</div>
) : (
<div style={responseContainerStyles}>
{status && <div>Status: {status}</div>}
Expand All @@ -29,6 +38,7 @@ export const ResponseContainer = ({ loading, status, error, data }) => (

ResponseContainer.propTypes = {
loading: PropTypes.bool,
uploadProgress: PropTypes.number,
status: PropTypes.number,
error: PropTypes.object,
data: PropTypes.object,
Expand Down
14 changes: 12 additions & 2 deletions stories/components/search-params-request/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export const SearchParamsRequest = ({ title, isFetch = true }) => {
const [todoId, setTodoId] = useState('1');
const [response, setResponse] = useState({});
const [loading, setLoading] = useState(false);
const [uploadProgress, setUploadProgress] = useState(0);

const handleSubmit = async (event) => {
event.preventDefault();
Expand All @@ -25,7 +26,12 @@ export const SearchParamsRequest = ({ title, isFetch = true }) => {
const fetchResponse = await callFetch({ url });
setResponse(fetchResponse);
} else {
const axiosResponse = await callAxios({ url });
const axiosResponse = await callAxios({
url,
onUploadProgress: (pev) => {
setUploadProgress(pev.loaded / pev.total);
},
});
setResponse(axiosResponse);
}
setLoading(false);
Expand All @@ -45,7 +51,11 @@ export const SearchParamsRequest = ({ title, isFetch = true }) => {
</div>
<input type="submit" value="Submit" style={buttonStyles} />
</form>
<ResponseContainer loading={loading} {...response} />
<ResponseContainer
uploadProgress={uploadProgress}
loading={loading}
{...response}
/>
</StoryContainer>
);
};
Expand Down
60 changes: 60 additions & 0 deletions stories/example.stories.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,55 @@ const mockData = [
},
];

const mockWithDelayData = [
{
url: 'https://jsonplaceholder.typicode.com/todos/:id',
method: 'GET',
status: 200,
delay: 5000,
response: {
id: '1',
name: 'Item 1',
},
},
{
url: 'https://jsonplaceholder.typicode.com/todos',
method: 'POST',
status: 201,
delay: 5000,
uploadFrameCount: 10,
response: {
message: 'New item created',
},
},
{
url: 'https://jsonplaceholder.typicode.com/todos/:id',
method: 'PUT',
status: 200,
delay: 5000,
uploadFrameCount: 100,
response: {
id: '1',
name: 'Item 1',
},
},
{
url: 'https://jsonplaceholder.typicode.com/todos/:id',
method: 'PATCH',
status: 204,
delay: 5000,
uploadFrameCount: 100,
response: null,
},
{
url: 'https://jsonplaceholder.typicode.com/todos/:id',
method: 'DELETE',
status: 202,
delay: 5000,
uploadFrameCount: 100,
response: null,
},
];
const mockCustomFunctionData = [
{
url: 'https://jsonplaceholder.typicode.com/todos/:id',
Expand Down Expand Up @@ -320,6 +369,17 @@ storiesOf('Examples/Custom Function/Axios', module)

storiesOf('Examples/Special Cases', module)
.addDecorator(withMock)
.add(
'Axios request with uploadProgress',
() => (
<NonGetRequest
title="Axios POST Request"
method="POST"
callApi={callAxios}
/>
),
{ mockData: mockWithDelayData }
)
.add(
'Same API calls multiple times',
() => (
Expand Down
2 changes: 2 additions & 0 deletions stories/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export const callAxios = async ({
method = DEFAULT_METHOD,
url = DEFAULT_URL,
body,
onUploadProgress,
}) => {
let data = null;
let error = null;
Expand All @@ -56,6 +57,7 @@ export const callAxios = async ({
url,
method,
data: body ? JSON.stringify(body) : undefined,
onUploadProgress,
});
data = response.data;
status = response.status;
Expand Down