Skip to content

Commit b307032

Browse files
committed
test: browser environment assertion unit tests
1 parent d58b20e commit b307032

2 files changed

Lines changed: 36 additions & 1 deletion

File tree

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { assertBrowserEnvironment } from '../assertBrowserEnvironment';
2+
3+
describe('assertBrowserEnvironment', () => {
4+
// jsdom provides a full DOM, so the browser APIs are present by default.
5+
test('does not throw when the DOM globals are available', () => {
6+
expect(() => assertBrowserEnvironment('EnrichedText')).not.toThrow();
7+
});
8+
9+
// Each of these globals is required - removing any one should trip the assertion.
10+
test.each(['window', 'document', 'DOMParser', 'Node'] as const)(
11+
'throws when %s is missing',
12+
(globalName) => {
13+
// Simulate an SSR environment where each global is undefined.
14+
const original = Object.getOwnPropertyDescriptor(globalThis, globalName);
15+
Object.defineProperty(globalThis, globalName, {
16+
value: undefined,
17+
configurable: true,
18+
});
19+
20+
try {
21+
expect(() => assertBrowserEnvironment('EnrichedText')).toThrow(
22+
/\[react-native-enriched\] EnrichedText is a client-only component/
23+
);
24+
} finally {
25+
Object.defineProperty(globalThis, globalName, original!);
26+
}
27+
}
28+
);
29+
});

src/web/assertBrowserEnvironment.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,13 @@
66
* This asserts a DOM is available and throws a clear error otherwise.
77
*/
88
export function assertBrowserEnvironment(componentName: string): void {
9-
if (typeof window === 'undefined' || typeof document === 'undefined') {
9+
const hasDOM =
10+
typeof window !== 'undefined' &&
11+
typeof document !== 'undefined' &&
12+
typeof DOMParser !== 'undefined' &&
13+
typeof Node !== 'undefined';
14+
15+
if (!hasDOM) {
1016
throw new Error(
1117
`[react-native-enriched] ${componentName} is a client-only component and cannot be rendered without a DOM. ` +
1218
`If you are running an SSR application, make sure the component is only rendered on the client.`

0 commit comments

Comments
 (0)