orphic-cypress
Version:
Set of utilities and typescript transformers to cover storybook stories with cypress component tests
173 lines • 8.46 kB
JavaScript
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.unitTestDecorator = exports.getStoryCyFromMdxCodeBlock = exports.UnitTest = exports.ParametersContext = void 0;
const addon_docs_1 = require("@storybook/addon-docs");
const components_1 = require("@storybook/components");
const react_1 = __importStar(require("react"));
const ts_dedent_1 = __importDefault(require("ts-dedent"));
const getDefaultDescription = (cyTest) => `should pass the following ${cyTest ? "cyTest" : "cy"} expectation`;
/** Get entries to map over to then display in each Preview component */
const getNormalizedCyTestEntries = (parameters, props) => {
var _a, _b;
if (!parameters)
return [];
const { cy, cyTest } = parameters;
if (cy) {
return typeof cy === "object"
? Object.entries(cy)
: [[(_a = props.description) !== null && _a !== void 0 ? _a : getDefaultDescription(false), cy]];
}
if (cyTest) {
return [[(_b = props.description) !== null && _b !== void 0 ? _b : getDefaultDescription(true), cyTest]];
}
return [];
};
/** Context for parameters used in unitTestDecorator */
exports.ParametersContext = (0, react_1.createContext)({});
/**
* Display test information for pure unit test stories.
* This is likey used in mdx files and must have a 'name' or 'id' which would appropriately
* match to the proper story.
* See [the task story](https://quotapath.github.io/orphic-cypress/storybook/?path=/docs/cypressutils-tasks--arbitrary-task#literate-testing)
* for detailed use.
* ```ts
* <Story
* name="ArbitraryTask"
* parameters={{
* cy: () =>
* cy.arbitraryTask(2).then(($num) => expect($num).to.equal(2)),
* }}
* >
* <UnitTest name="ArbitraryTask" />
* </Story>
* ```
*
* Or by providing the `unitTestDecorator` decorator and setting a `cyUnitTest`
* parameter to `true`
*/
const UnitTest = (props) => {
// lots of different possible ways of getting parameters in here
const docsContext = (0, react_1.useContext)(addon_docs_1.DocsContext);
const parametersContext = (0, react_1.useContext)(exports.ParametersContext);
let parameters = props.parameters;
const hasDocsContext = docsContext && Object.keys(docsContext).length > 0;
const hasParametersContext = parametersContext && Object.keys(parametersContext).length > 0;
if (!parameters) {
if (hasDocsContext) {
const storyId = (0, addon_docs_1.getStoryId)(props, docsContext);
const story = docsContext
.componentStories()
.find(({ id }) => id === storyId);
parameters = story === null || story === void 0 ? void 0 : story.parameters;
}
else if (hasParametersContext) {
parameters = parametersContext;
}
}
if (!parameters)
return null;
const cyMap = getNormalizedCyTestEntries(parameters, props);
const previews = cyMap.map(([key, orgCode], i) => {
const code = (0, ts_dedent_1.default)(orgCode.toString());
return (react_1.default.createElement("div", { key: String(key) || i },
key && react_1.default.createElement("div", { className: "orphic-cypress-unit-test" }, key),
!(props.isCodeBlock && hasDocsContext) && (react_1.default.createElement(components_1.Source, { language: "tsx", dark: true, format: false, code: code }))));
});
return react_1.default.createElement(react_1.default.Fragment, null, previews);
};
exports.UnitTest = UnitTest;
const regex = {
multilineInit: /^\s?\/\*/,
multilineClose: /\*\//,
comment: /^\s?(\/\/|\/\*\*|\*\/|\*)\s?/,
};
const partitionCommentsAndCode = (fnToParse) => {
const [comments, code] = [[], []];
const fnToParseSplit = fnToParse.split("\n");
let isMultiLine = regex.multilineInit.test(fnToParseSplit[0]) &&
!regex.multilineClose.test(fnToParseSplit[0]);
for (const line of fnToParse.split("\n")) {
if (code.length === 0 && (regex.comment.test(line) || isMultiLine)) {
if (regex.multilineClose.test(line))
isMultiLine = false;
const newComment = line.replace(regex.comment, "");
// strip empty lines
if (newComment.length)
comments.push(newComment);
}
else {
code.push(line);
}
}
// for now at least,
const joinedDescription = comments.length > 0 ? comments.join(" ") : "";
return [joinedDescription, code.join("\n")];
};
/**
* Gets the code block matching a story from the mdx page.
* Just a tad hacky with how its getting to the MDXContent
* @private
*/
const getStoryCyFromMdxCodeBlock = (parameters, storyName, functionize) => {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
const mdxContent = (_f = (_e = (_d = (_c = (_b = (_a = parameters === null || parameters === void 0 ? void 0 : parameters.docs) === null || _a === void 0 ? void 0 : _a.page) === null || _b === void 0 ? void 0 : _b.call(_a)) === null || _c === void 0 ? void 0 : _c.props) === null || _d === void 0 ? void 0 : _d.children) === null || _e === void 0 ? void 0 : _e.type) === null || _f === void 0 ? void 0 : _f.call(_e, {});
for (const child of (_h = (_g = mdxContent === null || mdxContent === void 0 ? void 0 : mdxContent.props) === null || _g === void 0 ? void 0 : _g.children) !== null && _h !== void 0 ? _h : []) {
if (((_j = child === null || child === void 0 ? void 0 : child.props) === null || _j === void 0 ? void 0 : _j.mdxType) === "pre") {
const childrenProps = (_k = child.props.children) === null || _k === void 0 ? void 0 : _k.props;
if (childrenProps.metastring === storyName) {
const [description, code] = partitionCommentsAndCode(childrenProps.children);
return {
[description.length ? description : getDefaultDescription(false)]: functionize ? `() => { ${code} }` : code,
};
}
}
}
return {};
};
exports.getStoryCyFromMdxCodeBlock = getStoryCyFromMdxCodeBlock;
/**
* A storybook decorator that provides a parameter context for the sake
* of showing UnitTest components in cypress and storybook canvas as opposed
* to just docs, and allows display without manually adding a UnitTest component
* via `cyUnitTest` parameter.
* TODO: types would be nice, but have been annoying
*/
const unitTestDecorator = (Story, context) => {
const parameters = { ...context.originalStoryFn, ...context.parameters };
if (parameters.cyCodeBlock) {
parameters.cy = (0, exports.getStoryCyFromMdxCodeBlock)(context.parameters, context.originalStoryFn.storyName);
}
return (react_1.default.createElement(exports.ParametersContext.Provider, { value: parameters },
react_1.default.createElement(Story, null),
(parameters.cyUnitTest || parameters.cyCodeBlock) && (react_1.default.createElement("span", { "data-cy": "cy-unit-test" },
react_1.default.createElement("br", null),
react_1.default.createElement(exports.UnitTest, { name: context.name, parameters: parameters, isCodeBlock: parameters.cyCodeBlock })))));
};
exports.unitTestDecorator = unitTestDecorator;
//# sourceMappingURL=UnitTest.js.map
;