UNPKG

@sprucelabs/test-utils

Version:

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

63 lines (62 loc) 2.39 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const assert_1 = __importDefault(require("./assert/assert")); class MockFetch { constructor() { this.requestLog = []; this.responses = { '*': new Response(JSON.stringify({ success: true, }), { status: 200 }), }; } buildFetch() { return async (url, init) => { this.requestLog.push({ url, init }); const key = this.generateResponseKey(url, init); return (this.responses[key] ?? this.responses['*']).clone(); }; } assertWasCalled(url, init) { assert_1.default.isTruthy(this.wasCalled, 'Expected fetch() to have been called.'); if (url) { const lastUrl = this.lastUrl; assert_1.default.isEqual(lastUrl, url, `Expected fetch() to have been called with URL "${url}", but it was called with "${lastUrl}".`); } if (init) { assert_1.default.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_1.default.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) { return `${url?.toString() ?? '*'}${init ? JSON.stringify(init) : ''}`; } } exports.default = MockFetch;