Skip to content

PROPOSAL: type-safe cy.task function #32014

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 3 commits into
base: develop
Choose a base branch
from

Conversation

alexsch01
Copy link
Contributor

@alexsch01 alexsch01 commented Jul 10, 2025

THIS IS A PROPOSAL

adds type-safety and autocomplete to cy.task function


cypress.config.js

const { defineConfig } = require('cypress')
const CypressTasks = require('./tasks')

const CypressConfig = defineConfig({
  e2e: {
    supportFile: false,
    setupNodeEvents(on, config) {
      on('task', CypressTasks)
    },
  },
})

module.exports = {
  ...CypressConfig,
  CypressTasks,
}

tasks.js

module.exports = {
  log(args) {
    console.log(args)
    return null;
  },

  /**
   * @param {any[]} args
   */
  logMany(args) {
    console.log(...args)
    return null;
  },

  getData() {
    return {
      response: {
        body: 'OK',
        status: 200,
      }
    }
  },

  /**
   * @param {string} x 
   * @returns {Promise<string>}
   */
  getSelf(x) {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(x);
      }, 5000);
    });
  },
}

cypress/e2e/spec.cy.js

it('Example of cy.task', () => {
  cy.task('logMany', [1, 2, 3, null, 5])

  cy.task('getData', undefined).then(data => {
    expect(data.response.status).to.eq(200)
    expect(data.response.body).to.eq('OK')
  })

  cy.task('getSelf', "=========").then((x) => {
    cy.task('log', x)
  })
})

jsconfig.json

{
  "compilerOptions": {
    "types": ["cypress"],
    "checkJs": true,
    "lib": ["ES2021", "DOM"],
    "module": "preserve",
    "strictNullChecks": true,
  },
  "exclude": ["node_modules"]
}

@cypress-app-bot
Copy link
Collaborator

@alexsch01 alexsch01 changed the title PROPOSAL: safe cy.task function PROPOSAL: type-safe cy.task function Jul 10, 2025
@alexsch01
Copy link
Contributor Author

alexsch01 commented Jul 14, 2025

@jennifer-shehane this PR draft adds type-safety to cy.task calls

Autocomplete works and will have a type error in VSCode when the types mismatch (input/output) or when the cy.task method is the wrong name

I don't know of a better way of reading from the Cypress Config File since this only has to do with the code editor types side

Please let me know what the team thinks about this feature

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants