All files / src execute.tsx

95.16% Statements 59/62
91.02% Branches 71/78
100% Functions 11/11
96.61% Lines 57/59

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195                                                  113x 400x                       400x                       113x         1566x         1566x     1566x 1566x 116x 116x   1566x     1566x   1566x 232x 58x   174x     1566x 1566x     1566x       3364x 3364x 3364x 3364x   3364x         1710x 1710x       1710x           3364x 522x 58x   464x 58x         58x             58x   58x 58x 58x         406x       2842x         2842x   116x           2842x 2842x   2030x 1624x         589x 589x 43x         406x 580x         363x 363x 241x   122x           812x   464x 178x              
import { storyNameFromExport } from "@storybook/csf";
import { composeStories } from "@storybook/testing-react";
import React from "react";
import * as ts from "typescript";
 
import type { Stories } from "./actions";
import { stubStoryActions } from "./actions";
import type { CyTestConfig } from "./config";
import { mockToCyIntercept } from "./intercept";
import { getStoryCyFromMdxCodeBlock } from "./storybook/UnitTest";
import type { StoryFileCy } from "./types";
 
/* istanbul ignore next */
class CyTestConfigError extends Error {
  constructor(format: "cyTest" | "object" | "function", storyTitle?: string) {
    super(
      `Opted out of allowing the ${format} format. See your setupNodeEvents` +
        ` and/or env["orphic-cypress"].format.${format} to alter the config, or update the test${
          storyTitle ? ` for ${storyTitle}` : ""
        } by changing it to a supported format or moving it to an external file`
    );
    Object.setPrototypeOf(this, new.target.prototype);
  }
}
 
const evalTranspile = (code: string) => {
  const transformed = eval(
    ts.transpile(
      `(React) => ${code}`,
      {
        jsx: ts.JsxEmit.React,
        module: ts.ModuleKind.ES2022,
        target: ts.ScriptTarget.ES2022,
        alwaysStrict: false,
      },
      "test.cy.tsx"
    )
  )(React);
  return eval(transformed);
};
 
/**
 * Execute standard cypress tests against a set of storybook components.
 * If the storybook story or object is normal, then it will perform a simple
 * 'mount' and expect no errors to throw. If the story or object has a `cy`
 * property, then the keys of that object will be used as 'it' descriptions
 * and each test there will be executed.
 *
 * @throws CyTestConfigError
 */
export const executeCyTests = <T extends StoryFileCy>(
  stories: T,
  describeText?: string
) => {
  const describeFn =
    stories.default.cyOnly || stories.default.parameters?.cyOnly
      ? describe.only
      : stories.default.cySkip || stories.default.parameters?.cySkip
      ? describe.skip
      : describe;
  describeFn(describeText || stories.default.title || "CyTest", () => {
    // adding `cy` property to default is a way to add hooks like `beforeEach`
    // for all tests in the file. I guess you could even write a test here.
    const defaultCy = stories.default.cy || stories.default.parameters?.cy;
    if (defaultCy) {
      Iif (typeof defaultCy === "string") evalTranspile(defaultCy)();
      else defaultCy();
    }
    const config: CyTestConfig = Cypress.env("orphic-cypress");
 
    const cyIncludeStories =
      stories.default.cyIncludeStories ||
      stories.default.parameters?.cyIncludeStories;
    if (cyIncludeStories) {
      if (cyIncludeStories === true) {
        delete stories.default.includeStories;
      } else {
        stories.default.includeStories = cyIncludeStories;
      }
    }
    const composed = composeStories(stories);
    const composedEntries = Object.entries(composed) as [
      [name: string, Comp: any]
    ];
    composedEntries.forEach(([name, Comp]) => {
      /* istanbul ignore next */
      if (typeof Comp !== "function") return;
 
      describe(storyNameFromExport(name), () => {
        const story = (stories as any as Stories)[name];
        const parameters = story.parameters || {};
        const cyTest = story.cyTest || parameters.cyTest;
 
        beforeEach(() => {
          /* istanbul ignore next */
          if (cyTest && config?.format?.cyTest === false) {
            throw new CyTestConfigError("cyTest", stories.default.title);
          }
          stubStoryActions(Comp, stories);
          const mockData = [
            ...(stories.default.parameters?.mockData || []),
            ...(Comp.parameters?.mockData || []),
          ];
          if (mockData.length > 0) mockToCyIntercept(mockData);
        });
 
        // cy test format where a function can then contain 'it's and 'before' etc
        // actions will be available at `cy.get("@actions")` or `this.actions`
        // and you can skip/only in the test
        if (cyTest) {
          if (typeof cyTest === "string") {
            return evalTranspile(cyTest)(Comp);
          }
          if (cyTest === true) {
            Iif (!parameters.cyCodeBlock) {
              throw new Error(
                "Provided `cyTest: true` but did not provide `cyCodeBlock`, which is required"
              );
            }
            const [description, cyTestFromBlock] = Object.entries(
              getStoryCyFromMdxCodeBlock(
                stories.default.parameters,
                story.storyName,
                true
              )
            )[0];
            story.cyTest = cyTestFromBlock;
 
            if (description) {
              return describe(description, () => {
                evalTranspile(cyTestFromBlock)(Comp);
              });
            }
            return evalTranspile(cyTestFromBlock)(Comp);
          }
          return cyTest(Comp);
        }
        // cy object format for a more streamlined test that does the mount for you
        const itFn =
          story.cyOnly || parameters.cyOnly
            ? it.only
            : story.cySkip || parameters.cySkip
            ? it.skip
            : it;
        if (parameters.cyCodeBlock) {
          // MUTATE STORY
          story.cy = getStoryCyFromMdxCodeBlock(
            stories.default.parameters,
            story.storyName,
            true
          );
        }
        const storyCy = story.cy || parameters.cy;
        if (storyCy) {
          // cy is a function directly
          if (typeof storyCy === "function" || typeof storyCy === "string") {
            return itFn("should satisfy a cy test expectation", function () {
              /* istanbul ignore next */
              if (config?.format?.function === false) {
                throw new CyTestConfigError("function", stories.default.title);
              }
              cy.mount(<Comp {...this.actions} />);
              if (typeof storyCy === "function") return storyCy.bind(this)();
              evalTranspile(storyCy).bind(this)();
            });
          }
          // otherwise cy is an object with story descriptions as keys and test
          // functions as values
          return Object.entries(storyCy).forEach(([desc, cyTest]) => {
            itFn(desc, function () {
              /* istanbul ignore next */
              if (config?.format?.object === false) {
                throw new CyTestConfigError("object", stories.default.title);
              }
              cy.mount(<Comp {...this.actions} />);
              if (typeof cyTest === "string") {
                evalTranspile(cyTest).bind(this)();
              } else {
                cyTest.bind(this)();
              }
            });
          });
        }
        // mdx files with no stories are docs only and will intentionally throw an error if rendered
        if (name !== "__page") {
          // no test defined, just check that it renders ok
          itFn(`${name} should render ok`, function () {
            cy.mount(<Comp {...this.actions} />);
          });
        }
      });
    });
  });
};