Skip to content

Commit

Permalink
universal-cookie - Disable accessing browser cookies on JSDOM (#227)
Browse files Browse the repository at this point in the history
  • Loading branch information
eXon committed Jul 4, 2019
1 parent 3e41f66 commit de3b2ce
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
7 changes: 5 additions & 2 deletions packages/universal-cookie/src/Cookies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
19 changes: 19 additions & 0 deletions packages/universal-cookie/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit de3b2ce

Please sign in to comment.