Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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