Search code examples
next.jscypress

When using nextjs with cypress to render coverage I keep getting error on declaring the global namespace


See example repo: https://github.com/inspiraller/nextjs-with-cypress-coverage

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./src/*"]
    },
    "types": ["cypress", "node"]
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts","./cypress.d.ts","./node_modules/cypress", "cypress/**/*.js"],
  "exclude": ["node_modules"],
  "ts-node": {
    "compilerOptions": {
      "module": "ESNext",
      "moduleResolution": "Node"
    }
  }
}

cypress.d.ts

/// <reference types="cypress" />

declare global {
  namespace Cypress {
    interface Chainable {
      mount: typeof mount
    }
  }
}

declare namespace Cypress {
  interface Chainable {
    /**
     * Custom command to select DOM element by data-cy attribute.
     * @example cy.dataCy('greeting')
     */
    dataCy(value: string): Chainable<Element>;
  }
}

I'm including the cypress.d.ts but it doesn't seem to be having any affect.

cypress/support/component.ts


/// <reference types="cypress" />
import '@cypress/code-coverage/support';


import './commands'
import { mount } from 'cypress/react18'

import '@/app/global.css';

Cypress.Commands.add('mount', mount) // Error here...

Argument of type '"mount"' is not assignable to parameter of type 'keyof Chainable'.ts(2345) Expect "mount" to exist.

I suspect cypress isn't honouring my tsonfig.json and is referring to its own tsconfig.json in the node_modules folder. How to override this?


Solution

  • Follow the pattern for cy.dataCy(), remove the declare global. It seems to fix the type error in component.ts

    /// <reference types="cypress" />
    
    // declare global {
      namespace Cypress {
        interface Chainable {
          mount: typeof mount
        }
      }
    // }
    
    declare namespace Cypress {
      interface Chainable {
        /**
         * Custom command to select DOM element by data-cy attribute.
         * @example cy.dataCy('greeting')
         */
        dataCy(value: string): Chainable<Element>;
      }
    }