/**
* Compares API responses for testing.
*
* @param {Array<Object>} expectedResponses - Array of expected API responses. Each object should have a 'data' property containing the expected data.
* @param {Array<Object>} actualResponses - Array of actual API responses. Each object should have a 'data' property containing the actual data.
* @param {string} [key='data'] - The key in the response object containing the data to compare. Defaults to 'data'.
* @returns {Promise<Array<string>>} - A promise that resolves to an array of strings, each representing a comparison error. Returns an empty array if all responses match.
*/
async function compareApiResponses(expectedResponses, actualResponses, key = 'data') {
const errors = [];
if (!expectedResponses || !actualResponses) {
return errors; // Return empty array if either input is missing
}
const expectedData = expectedResponses.map(resp => resp[key]);
const actualData = actualResponses.map(resp => resp[key]);
if(expectedData.length !== actualData.length){
errors.push("Arrays have different lengths: expected " + expectedData.length + ", actual " + actualData.length);
return errors;
}
for (let i = 0; i < expectedData.length; i++) {
if (typeof expectedData[i] === 'object' && typeof actualData[i] === 'object') {
if (!deepCompare(expectedData[i], actualData[i])) {
errors.push(`Index ${i}: Expected ${JSON.stringify(expectedData[i])}, but got ${JSON.stringify(actualData[i])}`);
}
} else if (expectedData[i] !== actualData[i]) {
errors.push(`Index ${i}: Expected ${expectedData[i]}, but got ${actualData[i]}`);
}
}
return errors;
function deepCompare(obj1, obj2) {
if (typeof obj1 !== 'object' || typeof obj2 !== 'object' || obj1 === null || obj2 === null) {
return obj1 === obj2; // handle primitive types and null
}
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) {
return false;
}
for (const key of keys1) {
if (!obj2.hasOwnProperty(key) || !deepCompare(obj1[key], obj2[key])) {
return false;
}
}
return true;
}
}
Add your comment