Skip to content

Instantly share code, notes, and snippets.

@djpogo
Last active February 7, 2020 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djpogo/0bd93602cc9b49ede429843d913494e8 to your computer and use it in GitHub Desktop.
Save djpogo/0bd93602cc9b49ede429843d913494e8 to your computer and use it in GitHub Desktop.
a unit testable document.cookie mock
// idea from here @see https://stackoverflow.com/questions/6456429/is-it-possible-to-mock-document-cookie-in-javascript
const fakeDocumentCookie = {
cookies: '',
get cookie() {
return this.cookies;
},
set cookie(cookieValue) {
const cookies = this.cookies.split(' ');
const cookieName = cookieValue.split('=').shift();
const cookieNameLength = cookieName.length;
let cookieIndex = -1;
cookies.forEach((value, index) => {
if (`${value.substr(0, cookieNameLength)}=` === `${cookieName}=`) {
cookieIndex = index;
}
});
if (cookieIndex > -1) {
cookies[cookieIndex] = `${cookieValue};`;
} else {
cookies.push(`${cookieValue};`);
}
this.cookies = cookies.join(' ').trim();
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment