cumulocity-cypress
Version:
Cypress commands for Cumulocity IoT
80 lines (79 loc) • 2.99 kB
JavaScript
import { C8yDefaultPactRecord, isPactError, } from "../../shared/c8ypact";
import { isCypressError } from "../../shared/c8yclient";
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;
const consoleProps = {
response: response || null,
matcher: matcher || null,
options,
info,
};
const logger = Cypress.log({
autoEnd: false,
name: "c8ymatch",
consoleProps: () => consoleProps,
message: matcher?.constructor.name || "-",
});
if (!pact || !_.isObjectLike(pact)) {
logger.end();
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;
}
consoleProps.isSchemaMatching = isSchemaMatching;
consoleProps.matcher = matcher;
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);
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,
});
}
}
catch (error) {
if (_.isFunction(Cypress.c8ypact.on?.matchingError)) {
Cypress.c8ypact.on.matchingError(matcher, error, options);
}
else if (options.failOnPactValidation === true) {
if (isCypressError(error) || isPactError(error)) {
throw error;
}
else {
throwError(`Matching schema failed. ${error}`);
}
}
}
finally {
logger.end();
}
});