function fetchUserInfo(userId) { return fetch(`https://api.github.com/users/${encodeURIComponent(userId)}`) .then(response => { if (!response.ok) { return Promise.reject(new Error(`${response.status}: ${response.statusText}`)); } else { return response.json(); } }); }
/* global setupPolly */ describe('REST Persister', function() { setupPolly({ adapters: ['fetch'], persister: 'rest' }); it('should work', async function() { const res = await fetch('https://jsonplaceholder.typicode.com/posts/1'); const post = await res.json(); expect(res.status).to.equal(200); expect(post.id).to.equal(1); }); });
function fetchUserInfo(userId) { fetch(`https://api.github.com/users/${encodeURIComponent(userId)}`) .then(response => { console.log(response.status); // エラーレスポンスが返されたことを検知する if (!response.ok) { console.error("エラーレスポンス", response); } else { return response.json().then(userInfo => { console.log(userInfo); }); } }).catch(error => { console.error(error); }); }
it('calls all intercept handlers', async function() { const { server } = this.polly; server.any().intercept(async (_, res) => { await server.timeout(5); res.status(200); }); server.any().intercept(async (_, res) => { await server.timeout(5); res.setHeader('x-foo', 'bar'); }); server.get('/ping').intercept((_, res) => res.json({ foo: 'bar' })); const res = await fetch('/ping'); const json = await res.json(); expect(res.status).to.equal(200); expect(res.headers.get('x-foo')).to.equal('bar'); expect(json).to.deep.equal({ foo: 'bar' }); });
const sendRequest = async (url, params = {}, callbacks = {}) => { const { onLoad, onSuccess, onFailure } = callbacks if (onLoad && typeof onLoad === 'function') onLoad() const resp = await fetch(url, params) const receiveBody = async (resp) => { if (resp.headers.get('Content-Type').includes('application/json')) { return await resp.json() } else { return await resp.text() } } // eslint-disable-next-line yoda if (200 <= resp.status && resp.status < 300) { let body if (resp.status !== 204) { body = await receiveBody(resp) } if (onSuccess && typeof onSuccess === 'function') onSuccess() return body } const body = await receiveBody(resp) if (onFailure && typeof onFailure === 'function') onFailure(body.errorMessage) throw new HTTPError(body.errorMessage) }
/* global setupPolly */ describe('Events', function() { setupPolly({ adapters: ['fetch'], persister: 'local-storage' }); it('can help test dynamic data', async function() { const { server } = this.polly; let numPosts = 0; server .get('https://jsonplaceholder.typicode.com/posts') .on('response', (_, res) => { numPosts = res.jsonBody().length; }); const res = await fetch('https://jsonplaceholder.typicode.com/posts'); const posts = await res.json(); expect(res.status).to.equal(200); expect(posts.length).to.equal(numPosts); }); });
function checkValidServiceWorker(swUrl, config) { // Check if the service worker can be found. If it can't reload the page. fetch(swUrl) .then(response => { // Ensure service worker exists, and that we really are getting a JS file. const contentType = response.headers.get('content-type'); if ( response.status === 404 || (contentType != null && contentType.indexOf('javascript') === -1) ) { // No service worker found. Probably a different app. Reload the page. navigator.serviceWorker.ready.then(registration => { registration.unregister().then(() => { window.location.reload(); }); }); } else { // Service worker found. Proceed as normal. registerValidSW(swUrl, config); } }) .catch(() => { console.log( 'No internet connection found. App is running in offline mode.' ); }); }
function fetchUserInfo(userId) { return fetch(`https://api.github.com/users/${encodeURIComponent(userId)}`) .then(response => { if (!response.ok) { return Promise.reject(new Error(`${response.status}: ${response.statusText}`)); } else { return response.json(); } }); }
/* global setupPolly */ describe('REST Persister', function() { setupPolly({ adapters: ['fetch'], persister: 'rest' }); it('should work', async function() { const res = await fetch('https://jsonplaceholder.typicode.com/posts/1'); const post = await res.json(); expect(res.status).to.equal(200); expect(post.id).to.equal(1); }); });
function fetchUserInfo(userId) { fetch(`https://api.github.com/users/${encodeURIComponent(userId)}`) .then(response => { console.log(response.status); // エラーレスポンスが返されたことを検知する if (!response.ok) { console.error("エラーレスポンス", response); } else { return response.json().then(userInfo => { console.log(userInfo); }); } }).catch(error => { console.error(error); }); }
it('calls all intercept handlers', async function() { const { server } = this.polly; server.any().intercept(async (_, res) => { await server.timeout(5); res.status(200); }); server.any().intercept(async (_, res) => { await server.timeout(5); res.setHeader('x-foo', 'bar'); }); server.get('/ping').intercept((_, res) => res.json({ foo: 'bar' })); const res = await fetch('/ping'); const json = await res.json(); expect(res.status).to.equal(200); expect(res.headers.get('x-foo')).to.equal('bar'); expect(json).to.deep.equal({ foo: 'bar' }); });
/* global setupPolly */ describe('Events', function() { setupPolly({ adapters: ['fetch'], persister: 'local-storage' }); it('can help test dynamic data', async function() { const { server } = this.polly; let numPosts = 0; server .get('https://jsonplaceholder.typicode.com/posts') .on('response', (_, res) => { numPosts = res.jsonBody().length; }); const res = await fetch('https://jsonplaceholder.typicode.com/posts'); const posts = await res.json(); expect(res.status).to.equal(200); expect(posts.length).to.equal(numPosts); }); });
const sendRequest = async (url, params = {}, callbacks = {}) => { const { onLoad, onSuccess, onFailure } = callbacks if (onLoad && typeof onLoad === 'function') onLoad() const resp = await fetch(url, params) const receiveBody = async (resp) => { if (resp.headers.get('Content-Type').includes('application/json')) { return await resp.json() } else { return await resp.text() } } // eslint-disable-next-line yoda if (200 <= resp.status && resp.status < 300) { let body if (resp.status !== 204) { body = await receiveBody(resp) } if (onSuccess && typeof onSuccess === 'function') onSuccess() return body } const body = await receiveBody(resp) if (onFailure && typeof onFailure === 'function') onFailure(body.errorMessage) throw new HTTPError(body.errorMessage) }
function checkValidServiceWorker(swUrl, config) { // Check if the service worker can be found. If it can't reload the page. fetch(swUrl) .then(response => { // Ensure service worker exists, and that we really are getting a JS file. const contentType = response.headers.get('content-type'); if ( response.status === 404 || (contentType != null && contentType.indexOf('javascript') === -1) ) { // No service worker found. Probably a different app. Reload the page. navigator.serviceWorker.ready.then(registration => { registration.unregister().then(() => { window.location.reload(); }); }); } else { // Service worker found. Proceed as normal. registerValidSW(swUrl, config); } }) .catch(() => { console.log( 'No internet connection found. App is running in offline mode.' ); }); }
function checkValidServiceWorker(swUrl, config) { // Check if the service worker can be found. If it can't reload the page. fetch(swUrl) .then(response => { // Ensure service worker exists, and that we really are getting a JS file. const contentType = response.headers.get('content-type'); if ( response.status === 404 || (contentType != null && contentType.indexOf('javascript') === -1) ) { // No service worker found. Probably a different app. Reload the page. navigator.serviceWorker.ready.then(registration => { registration.unregister().then(() => { window.location.reload(); }); }); } else { // Service worker found. Proceed as normal. registerValidSW(swUrl, config); } }) .catch(() => { console.log( 'No internet connection found. App is running in offline mode.' ); }); }