cumulocity-cypress
Version:
Cypress commands for Cumulocity IoT
74 lines (73 loc) • 2.84 kB
JavaScript
import { C8yDefaultPactRecord, } from "../../shared/c8ypact";
import { throwError } from "../utils";
import { C8yAjvSchemaMatcher } from "../../contrib/ajv";
const { _ } = Cypress;
Cypress.Commands.add("c8ymatch", (response, pact, info = {}, options = {}) => {
let matcher = Cypress.c8ypact.matcher;
if (!matcher && Cypress.c8ypact?.isEnabled() === true)
return;
if (!pact || !_.isObjectLike(pact)) {
throwError(`Matching requires object or schema to match. Received: ${pact}`);
}
const isSchemaMatching = !("request" in pact) && !("response" in pact);
if (isSchemaMatching) {
matcher =
options.schemaMatcher ??
Cypress.c8ypact?.schemaMatcher ??
new C8yAjvSchemaMatcher();
options.failOnPactValidation = true;
}
const consoleProps = {
response: response || null,
matcher: matcher || null,
options,
info,
isSchemaMatching,
};
const logger = Cypress.log({
autoEnd: false,
name: "c8ymatch",
consoleProps: () => consoleProps,
message: matcher?.constructor.name || "-",
});
if (matcher == null) {
logger.end();
return;
}
try {
let strictMatching = Cypress.c8ypact?.getConfigValue("strictMatching") === true;
if (options.strictMatching != null) {
strictMatching = options.strictMatching;
}
if (isSchemaMatching) {
const schema = pact;
_.extend(consoleProps, { response }, { schema });
matcher.match(response.body, schema, strictMatching);
}
else {
const matchingProperties = ["request", "response"];
const pactToMatch = _.pick(pact, matchingProperties);
Cypress.c8ypact.preprocessor?.apply(pactToMatch, info?.preprocessor ?? Cypress.c8ypact?.getConfigValue("preprocessor"));
const responseAsRecord = _.pick(C8yDefaultPactRecord.from(response), matchingProperties);
Cypress.c8ypact.preprocessor?.apply(responseAsRecord, info?.preprocessor ?? Cypress.c8ypact?.getConfigValue("preprocessor"));
_.extend(consoleProps, { responseAsRecord }, { response }, { pact: pactToMatch });
matcher.match(responseAsRecord, pactToMatch, {
strictMatching,
loggerProps: consoleProps,
schemaMatcher: Cypress.c8ypact.schemaMatcher,
requestId: options.requestId,
});
}
}
catch (error) {
if (_.isFunction(Cypress.c8ypact.on?.matchingError)) {
Cypress.c8ypact.on.matchingError(matcher, error, options);
}
else if (options.failOnPactValidation === true) {
throw error;
}
}
finally {
logger.end();
}
});