Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cypress custom command is not recognized when invoked

I've created the following custom command in my cypress/support/commands.js file.

Cypress.Commands.add("login", (username, password) => {
    cy.request({
        method: 'POST',
        form: true,
        url: '/test/login/',
        body: {'username': username, 'password': password}
    })
})

I had tests passing and login working before moving the login functionality to this custom command. I'm invoking it in my spec with cy.login(testuser, testpwd), but I'm getting the following error message: TypeError: cy.login is not a function. The docs say that /cypress/support/commands.js is loaded before any test files are evaluated, so I assumed that simply placing a custom command in there would make the command available. I'm running the tests through the local (GUI) test runner.

like image 965
Dan Swain Avatar asked Dec 07 '17 12:12

Dan Swain


People also ask

Where do I put custom commands in Cypress?

The best place to define the custom commands is in the cypress/support/commands. js file, as it loads before any of the test-script files.

What is custom command in Cypress?

Browser Automation with Cypress and Gherkin 2022 Cypress custom commands are described by users and not the default commands from Cypress. These customized commands are used to create the test steps that are repeated in an automation flow. We can add and overwrite an already pre-existing command.

Can Cypress commands return value?

You cannot assign or work with the return values of any Cypress command. Commands are enqueued and run asynchronously.

What is cy in Cypress?

A new Cypress chain always starts with cy. [command] , where what is yielded by the command establishes what other commands can be called next (chained).


2 Answers

For me it worked when I added the type signature of the custom command in the file cypress/support/index.d.ts. For more information visit: Cypress example - Custom Commands

declare namespace Cypress {
  interface Chainable {
    clearLocalStorageIframe(): void
  }
}

I am using 7.2.0 Cypress and command.ts and index.ts file extension I have changed it to .ts

like image 181
Deepanshu Singh Avatar answered Oct 23 '22 06:10

Deepanshu Singh


All the code and referenced modules in index.js are loaded before your test file. So you need to refer(require) commands.js in your index.js file. You can however import commands.js module directly in your test file but then you need to include it every test file. Recommended approach is to include it in index.js file and you are not worried about explicitly refer in your test files.

like image 30
Dinesh Kumar Avatar answered Oct 23 '22 05:10

Dinesh Kumar