Created
April 19, 2017 20:35
-
-
Save lucasbento/30ea6f82286d3f443930f49cd0b9fb89 to your computer and use it in GitHub Desktop.
Sanitize objects (also from mongoose) for Jest snapshot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Sanitize a test text removing the mentions of a `ObjectId` | |
* @param text {string} The text to be sanitized | |
* @returns {string} The sanitized text | |
*/ | |
export const sanitizeTestText = (text) => { | |
const values = text.split(' '); | |
return values.map((value) => { | |
// Remove any non-alphanumeric character from value | |
const cleanValue = value.replace(/[^a-z0-9]/gi, ''); | |
// Check if it's a valid `ObjectId`, if so, replace it with a static value | |
if (ObjectId.isValid(cleanValue)) { | |
return value.replace(cleanValue, 'ObjectId'); | |
} | |
return value; | |
}).join(' '); | |
}; | |
/** | |
* Sanitize a test object removing the mentions of a `ObjectId` | |
* @param payload {object} The object to be sanitized | |
* @param keys {[string]} Array of keys to redefine the value on the payload | |
* @param ignore {[string]} Array of keys to ignore | |
* @returns {object} The sanitized object | |
*/ | |
export const sanitizeTestObject = (payload, keys = ['id'], ignore = []) => { | |
return Object.keys(payload).reduce((sanitized, field) => { | |
if (ignore.indexOf(field) !== -1) { | |
return sanitized; | |
} | |
const value = payload[field]; | |
// If value is empty, return `EMPTY` value so it's easier to debug | |
if (!value && value !== 0) { | |
return { | |
...sanitized, | |
[field]: 'EMPTY', | |
}; | |
} | |
// Check if it's not an array and can be transformed into a string | |
if (!Array.isArray(value) && typeof value.toString === 'function') { | |
// Remove any non-alphanumeric character from value | |
const cleanValue = (value).toString().replace(/[^a-z0-9]/gi, ''); | |
// Check if it's a valid `ObjectId`, if so, replace it with a static value | |
if (ObjectId.isValid(cleanValue) && value.toString().indexOf(cleanValue) !== -1) { | |
return { | |
...sanitized, | |
[field]: value.toString().replace(cleanValue, 'ObjectId'), | |
}; | |
} | |
} | |
// If this current key is specified on the `keys` array, we simply redefine it | |
// so it stays the same on the snapshot | |
if (keys.indexOf(field) !== -1) { | |
return { | |
...sanitized, | |
[field]: `FROZEN-${field.toUpperCase()}`, | |
}; | |
} | |
// If it's an object, we call this function again to handle nested fields | |
if (typeof payload[field] === 'object') { | |
return { | |
...sanitized, | |
[field]: sanitizeTestObject(value, keys), | |
}; | |
} | |
return { | |
...sanitized, | |
[field]: value, | |
}; | |
}, {}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment