From de3b2ce6d7c2a1897e2c643fadbf4271e6c92d31 Mon Sep 17 00:00:00 2001 From: Benoit Tremblay Date: Wed, 3 Jul 2019 22:25:00 -0400 Subject: [PATCH] universal-cookie - Disable accessing browser cookies on JSDOM (#227) --- CHANGELOG.md | 1 + packages/universal-cookie/src/Cookies.ts | 7 +++++-- packages/universal-cookie/src/utils.ts | 19 +++++++++++++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 71ff135..49f9338 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ - Upgrade dependencies to last versions - Publish MIT license to NPM with the code (#224) - `universal-cookie`: Add support for generic type with reading cookies (#222) +- `universal-cookie`: Disable accessing browser cookies on JSDOM (#227) - `react-cookie`: Add `WrappedComponent` static property when using `withCookies` (#225) - `react-cookie`: Fix display name to include the original component name diff --git a/packages/universal-cookie/src/Cookies.ts b/packages/universal-cookie/src/Cookies.ts index 8be7b8c..11575ee 100644 --- a/packages/universal-cookie/src/Cookies.ts +++ b/packages/universal-cookie/src/Cookies.ts @@ -17,11 +17,14 @@ export default class Cookies { private cookies: { [name: string]: Cookie }; private changeListeners: CookieChangeListener[] = []; - private HAS_DOCUMENT_COOKIE: boolean; + private HAS_DOCUMENT_COOKIE: boolean = false; constructor(cookies?: string | object | null) { this.cookies = parseCookies(cookies); - this.HAS_DOCUMENT_COOKIE = hasDocumentCookie(); + + new Promise(() => { + this.HAS_DOCUMENT_COOKIE = hasDocumentCookie(); + }).catch(() => {}); } private _updateBrowserValues() { diff --git a/packages/universal-cookie/src/utils.ts b/packages/universal-cookie/src/utils.ts index 93a139c..71b408e 100644 --- a/packages/universal-cookie/src/utils.ts +++ b/packages/universal-cookie/src/utils.ts @@ -2,10 +2,29 @@ import * as cookie from 'cookie'; import { Cookie, CookieGetOptions } from './types'; export function hasDocumentCookie() { + // JSDOM does not support changing cookies, disable it for tests + if (isJsDom()) { + return false; + } + // Can we get/set cookies on document.cookie? return typeof document === 'object' && typeof document.cookie === 'string'; } +function isJsDom(): boolean { + if ( + typeof navigator !== 'object' || + typeof navigator.userAgent !== 'string' + ) { + return false; + } + + return ( + navigator.userAgent.indexOf('Node.js') >= 0 || + navigator.userAgent.indexOf('jsdom') >= 0 + ); +} + export function cleanCookies() { document.cookie.split(';').forEach(function(c) { document.cookie = c