hungry-fetch
Version:
A hungry fetch mock.
3 lines (2 loc) • 2.23 kB
JavaScript
function e(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function t(t){for(var r=1;r<arguments.length;r++){var o=null!=arguments[r]?arguments[r]:{};r%2?e(Object(o),!0).forEach(function(e){n(t,e,o[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(o)):e(Object(o)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(o,e))})}return t}function n(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class r{constructor(e,t={},n){this.url=void 0,this.additionalArgs=void 0,this.request=void 0,this.request=t,this.url=e,this.additionalArgs=n}json(){if("string"!=typeof this.request.body)throw Error("Can't parse json from "+typeof this.request.body);return JSON.parse(this.request.body)}body(){return this.request.body}}let o=[],i=[];function s(e,t){return e===t?1:"*"===t?.1:function(e,t){const n=e.split("/"),r=t.split("/");return n.length===r.length&&r.every((e,t)=>"*"===e||n[t]===e)}(e,t)?.5:0}function c(){o=[],i=[]}function u(){return o}function l(){if(0===o.length)throw new Error("fetch(…) has not been called!");return o[o.length-1]}function f(){if(1!==o.length)throw new Error(`fetch(…) not called exactly one time! It was called ${o.length} times.`);return l()}function a(e,t,n={},r=!0){i.push({pattern:e,body:t,resolve:r,config:n})}("undefined"!=typeof window?window:global).fetch=(e,n,...c)=>new Promise((u,l)=>{o.push(new r(e,n,c));const f=function(e){return 0===i.length?null:i.reduce((t,n)=>{const r=s(e,n.pattern);return 0===r?t:null===t||r>s(e,t.pattern)?n:t},null)}(e);if(f){const e=function(e){let n,r;"object"==typeof e.body?(n=JSON.stringify(e.body),r="application/json"):(n=e.body,r="text/plain");const{config:o}=e;return new Response(n,{headers:t({"Content-Type":o.contentType||r},o.headers||{}),status:o.status||200})}(f);f.resolve?u(e):l(new Error("Failed to fetch"))}else u()});export{u as calls,c as clear,l as lastCall,a as mockResponse,f as singleCall};
//# sourceMappingURL=hungry-fetch.modern.mjs.map