From c9984e4b840b86210696effaebec029acf422556 Mon Sep 17 00:00:00 2001 From: Alex Freska Date: Tue, 20 Feb 2024 10:34:02 -0500 Subject: [PATCH] chore: renterd jest config --- apps/renterd/jest.config.ts | 1 + apps/renterd/jest.polyfills.js | 31 +++++++++++++++++++++++++++++++ apps/renterd/mock/mock.tsx | 31 +++++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+) create mode 100644 apps/renterd/jest.polyfills.js create mode 100644 apps/renterd/mock/mock.tsx diff --git a/apps/renterd/jest.config.ts b/apps/renterd/jest.config.ts index 5c308af23..79a400a97 100644 --- a/apps/renterd/jest.config.ts +++ b/apps/renterd/jest.config.ts @@ -16,4 +16,5 @@ export default { 'next/dist/build/jest/__mocks__/nextFontMock.js' ), }, + setupFiles: ['./jest.polyfills.js'], } diff --git a/apps/renterd/jest.polyfills.js b/apps/renterd/jest.polyfills.js new file mode 100644 index 000000000..5cc3a0873 --- /dev/null +++ b/apps/renterd/jest.polyfills.js @@ -0,0 +1,31 @@ +// jest.polyfills.js +/** + * @note The block below contains polyfills for Node.js globals + * required for Jest to function when running JSDOM tests. + * These HAVE to be require's and HAVE to be in this exact + * order, since "undici" depends on the "TextEncoder" global API. + * + * Consider migrating to a more modern test runner if + * you don't want to deal with this. + */ + +const { TextDecoder, TextEncoder, ReadableStream } = require('node:util') + +Object.defineProperties(globalThis, { + TextDecoder: { value: TextDecoder }, + TextEncoder: { value: TextEncoder }, + ReadableStream: { value: ReadableStream }, +}) + +const { Blob, File } = require('node:buffer') +const { fetch, Headers, FormData, Request, Response } = require('undici') + +Object.defineProperties(globalThis, { + fetch: { value: fetch, writable: true }, + Blob: { value: Blob }, + File: { value: File }, + Headers: { value: Headers }, + FormData: { value: FormData }, + Request: { value: Request }, + Response: { value: Response }, +}) diff --git a/apps/renterd/mock/mock.tsx b/apps/renterd/mock/mock.tsx new file mode 100644 index 000000000..90bef6e72 --- /dev/null +++ b/apps/renterd/mock/mock.tsx @@ -0,0 +1,31 @@ +import { SetupServer } from 'msw/node' +import { HttpResponse, http } from 'msw' +import { Bucket } from '@siafoundation/react-renterd' + +export function mockApiBusBuckets(server: SetupServer) { + server.use( + http.get('/api/bus/buckets', () => { + return HttpResponse.json([ + { + name: 'foo', + policy: { + publicReadAccess: true, + }, + }, + ] as Bucket[]) + }) + ) +} + +export function mockMatchMedia() { + window.matchMedia = jest.fn().mockImplementation((query) => ({ + matches: false, + media: query, + onchange: null, + addListener: jest.fn(), + removeListener: jest.fn(), + addEventListener: jest.fn(), + removeEventListener: jest.fn(), + dispatchEvent: jest.fn(), + })) +}