1. /**
  2. * Compares API responses for testing.
  3. *
  4. * @param {Array<Object>} expectedResponses - Array of expected API responses. Each object should have a 'data' property containing the expected data.
  5. * @param {Array<Object>} actualResponses - Array of actual API responses. Each object should have a 'data' property containing the actual data.
  6. * @param {string} [key='data'] - The key in the response object containing the data to compare. Defaults to 'data'.
  7. * @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.
  8. */
  9. async function compareApiResponses(expectedResponses, actualResponses, key = 'data') {
  10. const errors = [];
  11. if (!expectedResponses || !actualResponses) {
  12. return errors; // Return empty array if either input is missing
  13. }
  14. const expectedData = expectedResponses.map(resp => resp[key]);
  15. const actualData = actualResponses.map(resp => resp[key]);
  16. if(expectedData.length !== actualData.length){
  17. errors.push("Arrays have different lengths: expected " + expectedData.length + ", actual " + actualData.length);
  18. return errors;
  19. }
  20. for (let i = 0; i < expectedData.length; i++) {
  21. if (typeof expectedData[i] === 'object' && typeof actualData[i] === 'object') {
  22. if (!deepCompare(expectedData[i], actualData[i])) {
  23. errors.push(`Index ${i}: Expected ${JSON.stringify(expectedData[i])}, but got ${JSON.stringify(actualData[i])}`);
  24. }
  25. } else if (expectedData[i] !== actualData[i]) {
  26. errors.push(`Index ${i}: Expected ${expectedData[i]}, but got ${actualData[i]}`);
  27. }
  28. }
  29. return errors;
  30. function deepCompare(obj1, obj2) {
  31. if (typeof obj1 !== 'object' || typeof obj2 !== 'object' || obj1 === null || obj2 === null) {
  32. return obj1 === obj2; // handle primitive types and null
  33. }
  34. const keys1 = Object.keys(obj1);
  35. const keys2 = Object.keys(obj2);
  36. if (keys1.length !== keys2.length) {
  37. return false;
  38. }
  39. for (const key of keys1) {
  40. if (!obj2.hasOwnProperty(key) || !deepCompare(obj1[key], obj2[key])) {
  41. return false;
  42. }
  43. }
  44. return true;
  45. }
  46. }

Add your comment