UNPKG

@sprucelabs/test-utils

Version:

Helpful utilities to make asserting more complicated conditions quick and easy! ⚡️

59 lines (58 loc) 2.25 kB
import assert from './assert/assert.js'; export default class MockFetch { constructor() { this.requestLog = []; this.responses = { '*': new Response(JSON.stringify({ success: true, }), { status: 200 }), }; } buildFetch() { return async (url, init) => { var _a; this.requestLog.push({ url, init }); const key = this.generateResponseKey(url, init); return ((_a = this.responses[key]) !== null && _a !== void 0 ? _a : this.responses['*']).clone(); }; } assertWasCalled(url, init) { assert.isTruthy(this.wasCalled, 'Expected fetch() to have been called.'); if (url) { const lastUrl = this.lastUrl; assert.isEqual(lastUrl, url, `Expected fetch() to have been called with URL "${url}", but it was called with "${lastUrl}".`); } if (init) { assert.isEqualDeep(this.lastInit, init, `Expected fetch() to have been called with init "${JSON.stringify(init)}", but it was called with "${JSON.stringify(this.lastInit)}".`); } } get lastInit() { return this.requestLog[this.requestLog.length - 1].init; } get wasCalled() { return this.requestLog.length > 0; } get urlsCalled() { return this.requestLog.map((req) => req.url); } get lastUrl() { return this.urlsCalled[this.urlsCalled.length - 1]; } assertMadeRequests(expected) { const expectedAsObjects = expected.map((req) => { if (typeof req === 'string' || req instanceof URL) { return { url: req, init: undefined }; } return req; }); assert.isEqualDeep(this.requestLog, expectedAsObjects, `Expected fetch() to have been called with URL and init combinations as specified.`); } setResponse(response, url, init) { const key = this.generateResponseKey(url, init); this.responses[key] = response; } generateResponseKey(url, init) { var _a; return `${(_a = url === null || url === void 0 ? void 0 : url.toString()) !== null && _a !== void 0 ? _a : '*'}${init ? JSON.stringify(init) : ''}`; } }