cumulocity-cypress
Version:
Cypress commands for Cumulocity IoT
79 lines (78 loc) • 2.99 kB
JavaScript
import { mount } from "cypress/angular";
import "./auth";
import "../../c8ypact";
import "./intercept";
import "./oauthlogin";
import { FetchClient } from "@c8y/client";
import { getAuthOptionsFromCypressEnv, getBaseUrlFromEnv } from "../utils";
Cypress.Commands.add("mount",
// @ts-expect-error
{ prevSubject: "optional" }, (subject, ...args) => {
const [component, options = {}] = args;
if (Cypress.c8ypact == null || Cypress.c8ypact.isEnabled() === false) {
return mount(component, options);
}
const consoleProps = {};
const logger = Cypress.log({
autoEnd: false,
name: "mount",
// @ts-expect-error
message: isClass(component) ? component.name : component,
consoleProps: () => consoleProps,
});
let baseUrl = getBaseUrlFromEnv();
if (!baseUrl && !Cypress.c8ypact.isRecordingEnabled()) {
baseUrl = Cypress.c8ypact.current?.info.baseUrl;
}
const auth = subject || getAuthOptionsFromCypressEnv();
consoleProps.baseUrl = baseUrl;
consoleProps.auth = auth || null;
consoleProps.options = options;
if (!baseUrl) {
logger.end();
const error = new Error("No base URL configured. cy.mount requires a base url. For component testing use C8Y_BASEURL or C8Y_HOST env variable.");
error.name = "C8yPactError";
throw error;
}
const requiresLogin = Cypress.c8ypact.isRecordingEnabled() || Cypress.c8ypact.mode() === "forward";
consoleProps.isRecordingEnabled = requiresLogin;
const strictMocking = Cypress.c8ypact?.getConfigValue("strictMocking") === true;
consoleProps.strictMocking = strictMocking;
const registerFetchClient = (auth) => {
const fetchClient = Cypress.c8ypact.createFetchClient(auth,
// might use window.location if baseUrl is relative (does not start with http)
baseUrl || "");
if (!fetchClient) {
return;
}
const optionsWithProviders = options;
const providers = optionsWithProviders.providers || [];
if (!providers.some((provider) => provider.provide === FetchClient)) {
providers.push({
provide: FetchClient,
useValue: fetchClient,
});
optionsWithProviders.providers = providers;
consoleProps.providers = providers;
}
};
const getAuthOptions = () => {
if (auth != null &&
(requiresLogin === true || strictMocking === false) &&
(auth.token == null || auth.xsrfToken == null)) {
return cy.oauthLogin(auth);
}
return cy.wrap(auth, { log: false });
};
return getAuthOptions().then((a) => {
registerFetchClient(a);
logger.end();
return mount(component, options);
});
});
function isClass(component) {
return (component &&
typeof component === "function" &&
!!component.prototype &&
component.constructor != null);
}