Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JohnathanWeisner/4131b0f2104b13d5b0ceaeaafe7f9d48 to your computer and use it in GitHub Desktop.
Save JohnathanWeisner/4131b0f2104b13d5b0ceaeaafe7f9d48 to your computer and use it in GitHub Desktop.
mockfetch.js
import { comments } from "./mock-response.json";
const mockResponse = (response) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
success: 200,
json: () =>
new Promise((resolve) => {
return resolve(response);
}),
});
}, 2000);
});
};
export const fetch = (url, { body } = {}) => {
if (url === "/comments/verify") {
// Simulate a failing fetch
if (Math.random() > 0.5) {
return Promise.reject("No connection.");
}
if (!body?.postId) {
return Promise.reject("Missing postId");
}
if (typeof body?.isVerified === "undefined") {
return Promise.reject("Missing isVerified");
}
const { postId, isVerified } = body;
const comment = comments.find((comment) => comment.postId === postId);
if (!comment) {
return Promise.reject("No comment found with that postId.");
}
comment.isVerified = isVerified;
return mockResponse({ comment });
} else if (url === "/comments") {
return mockResponse({ comments });
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment