import { when } from 'jest-when'; import { Serializable } from '../src/types'; export interface MockRequestOptions { url: string method?: string headers?: Record credentials?: string body?: Serializable } export interface MockResponseOptions { status?: number body?: Serializable } export default class FetchMockBuilder { req: MockRequestOptions res: MockResponseOptions constructor(req: MockRequestOptions, res: MockResponseOptions) { this.req = { method: 'GET', credentials: 'same-origin', headers: {}, ...req, }; this.res = { status: 200, body: '', ...res, }; } buildInit(): Partial { const init: Partial = {}; init.method = this.req.method; if (this.req.method) { init.method = this.req.method; } if (this.req.headers) { init.headers = this.req.headers; } if (this.req.credentials) { init.credentials = this.req.credentials; } if (this.req.body) { init.body = JSON.stringify(this.req.body); } return init; } build(): jest.Mock { const text = jest.fn(); when(text).calledWith().mockResolvedValue(JSON.stringify(this.res.body)); const mockResponse = { status: this.res.status, text, }; const mockFetch = jest.fn(); when(mockFetch) .expectCalledWith(this.req.url, this.buildInit()) .mockResolvedValue(mockResponse); return mockFetch; } }