From b4ac82921d13bd539f1d53ec9c6345c91dc6637b Mon Sep 17 00:00:00 2001 From: Artem Zakharchenko Date: Tue, 24 Jan 2023 16:27:45 +0100 Subject: [PATCH] feat: throw and suggest a URL polyfill for React Native (#1520) --- src/index.ts | 7 +++++++ src/utils/internal/checkGlobals.ts | 17 +++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 src/utils/internal/checkGlobals.ts diff --git a/src/index.ts b/src/index.ts index f4cc2e26c..f0de4b04a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,5 @@ import * as context from './context' +import { checkGlobals } from './utils/internal/checkGlobals' export { context } export { setupWorker } from './setupWorker/setupWorker' @@ -65,3 +66,9 @@ export type { export type { Path, PathParams, Match } from './utils/matching/matchRequestUrl' export type { DelayMode } from './context/delay' export { ParsedGraphQLRequest } from './utils/internal/parseGraphQLRequest' + +// Validate environmental globals before executing any code. +// This ensures that the library gives user-friendly errors +// when ran in the environments that require additional polyfills +// from the end user. +checkGlobals() diff --git a/src/utils/internal/checkGlobals.ts b/src/utils/internal/checkGlobals.ts new file mode 100644 index 000000000..ad765eaa9 --- /dev/null +++ b/src/utils/internal/checkGlobals.ts @@ -0,0 +1,17 @@ +import { invariant } from 'outvariant' +import { devUtils } from './devUtils' + +export function checkGlobals() { + /** + * MSW expects the "URL" constructor to be defined. + * It's not present in React Native so suggest a polyfill + * instead of failing silently. + * @see https://github.com/mswjs/msw/issues/1408 + */ + invariant( + typeof URL !== 'undefined', + devUtils.formatMessage( + `Global "URL" class is not defined. This likely means that you're running MSW in an environment that doesn't support all Node.js standard API (e.g. React Native). If that's the case, please use an appropriate polyfill for the "URL" class, like "react-native-url-polyfill".`, + ), + ) +}