Skip to content

Instantly share code, notes, and snippets.

@mr-feek
Last active September 18, 2024 16:41
Show Gist options
  • Select an option

  • Save mr-feek/53771820a82fd16715f71f43e9416fad to your computer and use it in GitHub Desktop.

Select an option

Save mr-feek/53771820a82fd16715f71f43e9416fad to your computer and use it in GitHub Desktop.
assertBodyStructure adonis macro
ApiResponse.macro('assertBodyStructure', function (expected: any) {
this.ensureHasAssert();
const assertHasShape = (expectedShape: any, actual: any) => {
this.assert!.equal(
types.lookup(actual),
types.lookup(expectedShape),
`failed when evaluating ${JSON.stringify(
expectedShape,
null,
' ',
)} within actual: \n${JSON.stringify(actual, null, ' ')}\n`,
);
if (expectedShape === '*') {
this.assert!.isNotNull(actual);
return;
}
if (types.lookup(actual) === 'array') {
this.assert!.isArray(expectedShape);
// check if we are expecting an empty array
if (expectedShape.length === 0) {
this.assert!.lengthOf(actual, 0);
return;
}
// if we have an array, ensure every item in the array matches the expected shape
this.assert!.isTrue(
actual.length > 0,
`cannot find expected ${JSON.stringify(
expectedShape[0],
null,
' ',
)} within actual: \n${JSON.stringify(actual, null, ' ')}`,
);
actual.forEach(responseItem => {
assertHasShape(expectedShape[0], responseItem);
});
return;
}
if (types.lookup(actual) === 'object') {
for (const expectedKey in expectedShape) {
this.assert!.property(
actual,
expectedKey,
`cannot find expected property '${expectedKey}' within actual: \n${JSON.stringify(
actual,
null,
' ',
)}`,
);
if (expectedShape[expectedKey] === '*') {
continue;
}
if (typeof expectedShape[expectedKey] === 'object') {
// woo recursion
assertHasShape(expectedShape[expectedKey], actual[expectedKey]);
continue;
}
throw new Error(
`assertBodyStructure does not yet know how to handle ${expectedShape[expectedKey]}`,
);
}
return;
}
throw new Error(`assertBodyStructure does not yet know how to handle type ${types.lookup(actual)}`);
};
assertHasShape(expected, this.body());
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment