Skip to content
Back to Blog
Cypress

Catch import cycles before Cypress loads a single spec

An import cycle in your page objects can make a whole spec file vanish. dpdm finds the cycle in seconds, in CI and inside setupNodeEvents.

Catch import cycles before Cypress loads a single spec
100% Human-Authored: All engineering insights, production war stories, and code were written by Marcelo Costa with zero AI involvement in authoring. AI was used solely for multilingual translations.

Zero tests executed. One generated failure: An uncaught error was detected outside of a test.

If your page objects import each other and a whole spec file suddenly does that, stop debugging the test logic and look for a circular import first. I told the full story in The circular dependency that ate my whole spec file. This is the short how-to for the guard that keeps cycles out.

dpdm walks your TypeScript import graph without compiling anything and prints every cycle it finds, in seconds.

The npm script

One line in package.json:

"check:cycles": "dpdm -T --circular --no-warning --no-tree --exit-code circular:1 \"cypress/**/*.ts\""

--circular prints the cycles, and --no-tree and --no-warning drop the noise. -T strips TypeScript types before the analysis, so an import type doesn't count as an edge (it disappears at compile time anyway).

The flag you can't forget is --exit-code circular:1. Without it, dpdm prints the cycle, exits 0, and your CI stays green. Ask me how I know.

I run it in three places:

pre-commit hook   → when TypeScript files are staged
CI                → before the suite starts
setupNodeEvents   → for anyone who launches cypress open directly

dpdm output listing one cycle between two page objects, then exit code 1

Running it inside Cypress too

The third check is for the teammate who runs cypress open without touching any npm script. dpdm also has a Node API, so setupNodeEvents can refuse to start when a cycle exists:

import { defineConfig } from 'cypress';
import path from 'node:path';
import { parseDependencyTree, parseCircular } from 'dpdm';

async function failOnImportCycles(projectRoot: string) {
  const previousCwd = process.cwd();
  process.chdir(projectRoot);
  try {
    const graph = await parseDependencyTree('cypress/**/*.ts', { context: projectRoot, transform: true });
    const cycles = parseCircular(graph);
    if (cycles.length) {
      throw new Error(`Import cycles found:\n${cycles.map((cycle) => cycle.join(' -> ')).join('\n')}`);
    }
  } finally {
    process.chdir(previousCwd);
  }
}

export default defineConfig({
  e2e: {
    async setupNodeEvents(on, config) {
      await failOnImportCycles(path.resolve(__dirname));
      return config;
    },
  },
});

If setupNodeEvents throws, Cypress prints the error and never opens a spec. You get the exact cycle in the message instead of a spec file that quietly registered zero tests.

Gotcha: the working directory

Keep the process.chdir dance. Cypress evaluates the config file in a child process whose working directory is the folder that holds the config. If your configs live in a subfolder like cypress/configs/, a relative glob such as cypress/**/*.ts matches nothing, and dpdm reports zero cycles with a straight face. Switch to the project root before parsing, and restore the old directory in finally.

How I check it works

  1. Plant a cycle: a.ts imports a value from ./b, and b.ts imports a value from ./a.
  2. Run npm run check:cycles. Both files should appear in the cycle list.
  3. Run echo $? (or $LASTEXITCODE in PowerShell). It must print 1.
  4. Remove one import and rerun. dpdm prints ✅ Congratulations, no circular dependency was found in your project. and exits 0.

Then try it once inside Cypress: leave the cycle in place, run cypress open, and make sure it refuses to start.

Page objects that point at each other without a cycle

Fluent page objects often return each other. When one side only needs the other as a type, use import type. With -T, dpdm ignores that edge, and at runtime it doesn't exist:

import { OrderDetailPage } from './order-detail.page';

export class OrdersPage {
  visit(): this {
    cy.visit('/orders');
    return this;
  }

  openOrder(orderId: string): OrderDetailPage {
    cy.contains('[data-cy="order-row"]', orderId).click();
    return new OrderDetailPage();
  }
}
import type { OrdersPage } from './orders.page';

export class OrderDetailPage {
  shouldShowStatus(status: string): this {
    cy.get('[data-cy="order-status"]').should('contain.text', status);
    return this;
  }

  backTo(orders: OrdersPage): OrdersPage {
    cy.get('[data-cy="back-to-orders"]').click();
    return orders;
  }
}

The first file is cypress/pages/orders.page.ts, the second is cypress/pages/order-detail.page.ts. OrdersPage needs OrderDetailPage as a value, because it calls new. OrderDetailPage only needs OrdersPage as a type, so the runtime graph has one edge and no loop.

The same two page objects: value imports in both directions make a cycle and exit code 1; switching one side to import type leaves one runtime edge and exit code 0

Recap

  • Add dpdm -T --circular --no-warning --no-tree --exit-code circular:1 as an npm script. Don't skip --exit-code circular:1.
  • Run it in your pre-commit hook and in CI.
  • Call the Node API from setupNodeEvents after a chdir to the project root, so cypress open fails fast too.
  • Break mutual page-object imports with import type wherever one side only needs the type.

Three checks for one bug sounds paranoid, until you lose half a day to a spec file that silently ran nothing. Each one finishes in seconds. Happy testing!