cy.lighthouse and cy.pa11y not working in files like .spec.ts or .ts

Viewed 619

I wanted to make a lighthouse test using cypress-audit, but after doing everything they said on https://www.npmjs.com/package/cypress-audit it doesn't work. I can use "cy.lighthouse()" in the cypress/support/commands.js, but not in files with extension like .spec.ts or .ts ( i get "Property 'lighthouse' does not exist on type 'cy & EventEmitter'.ts(2339)" error ). I already tried to find any solutions on the internet, but nothing worked.

package.json:

{
  "name": "XXXX",
  "version": "0.0.1",
  "description": "",
  "scripts": {
    "start_cypress": "npx cypress open",
    "install_dependencies": "npm install"
  },
  "author": "",
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.0",
    "babel-preset-stage-3": "^6.24.1",
    "cross-env": "^5.0.5",
    "cypress": "^9.3.1",
    "cypress-audit": "^1.1.0",
    "typescript": "^4.5.4",
    "webpack": "^5.66.0",
    "webpack-dev-server": "^4.7.3"
  }
}

cypress/plugins/index.js:

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

/**
 * @type {Cypress.PluginConfig}
 */

const { lighthouse, pa11y, prepareAudit } = require("cypress-audit");

module.exports = (on, config) => {
  on("before:browser:launch", (browser = {}, launchOptions) => {
    prepareAudit(launchOptions);
  });

  on("task", {
    lighthouse: lighthouse(), // calling the function is important
    pa11y: pa11y(), // calling the function is important
  });
}

cypress/support/commands.js:

import 'cypress-audit/commands';

CypressAudit.spec.ts:

describe('Audits', () => {
    beforeEach(() => {
        cy.visit('/');
    });

    it("should pass the audits", function () {
        cy.lighthouse();
        cy.pa11y();
    });
});
2 Answers

There are some type defs in the cypress-audit package that should be kicking in. Perhaps it's the mixture of ts and js files?

Try adding these to /cypress/support/index.ts

  interface Chainable<Subject> {
    /**
     * Runs a lighthouse audit
     * @example
     * cy.lighthouse(thresholds,opts,config)
     */
    lighthouse(thresholds?: LighthouseThresholds, opts?: any, config?: any);

    /**
     * Runs a pa11y audit
     * @example
     * cy.pa11y(opts)
     */
    pa11y(opts?: Options);

  }

Turns out I wanted to use "cy.lighthouse()" in file.spec.ts (I'm using typescript) and after checking everything there is in the example, I noticed that the example is in file.spec.js. It turns out that even though cypress is working with typescript, this command works only in javascript.

Related