Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cypress doesn't see custom cy. commands

Cypress can't import custom command

commands.js

Cypress.Commands.add('generateToken', ({secret}) => {
    const totp = require('totp-generator');
    const token = totp(secret); 
    });

support/index.js

import './commands'

test.spec.ts

/// <reference types="Cypress" />

context('Actions', () => {
    beforeEach(() => {})
  })
    it('Main test', () => {
        cy.generateToken('XXXX');
    })

All the time generateToken() is underlined in test.spec.ts and error appears:

Property 'generateToken' does not exist on type 'cy'.

index.js and commands.js were not moved from original directories. cypress.json file is empty.

like image 659
A. Makarevich Avatar asked Oct 10 '19 14:10

A. Makarevich


3 Answers

Since the proposed answer of nshirley did not work for me, I found this comment. It is very similar but adds declare global at the top, to declare these custom commands on a global scope.

Here is a working example:

cypress/support/commands.ts:

declare global {
  namespace Cypress {
    interface Chainable<Subject> {
      /**
       * Provides a working example
       */
      generateToken(secret: any): Cypress.Chainable<Element>;
    }
  }
}

const generateToken = (secret: any) => {
  // Your Code
};

Cypress.Commands.add("generateToken", generateToken);

And in your test you can just use it:

cy.generateToken("Example");

As you can see, you can even provide some documentation for your methods, but that is completely optional.

like image 97
Khaido Avatar answered Oct 26 '22 02:10

Khaido


Here is how I get TypeScript to see my custom commands:

commands.ts

declare namespace Cypress {
  interface Chainable<Subject> {
    generateToken(secret: any): Cypres.Chainable<void>;
  }
}

function generateToken(secret: any): void {
  // Generate token
}

Cypress.Commands.add('generateToken', generateToken);

test.spec.ts

cy.generateToken(secret);
like image 20
HaveSpacesuit Avatar answered Oct 26 '22 02:10

HaveSpacesuit


Since your spec is a typescript file, did you add a new types definition for the support/index.js?

Their documentation seems to outline it pretty well here. Only thing that is different with their example though is that you're not returning anything from generateToken so I don't think you can place it into the global Chainable interface.

You could try adding this in a support/index.d.ts file and see if it yells at you

declare namespace Cypress {
  interface Chainable {
    generateToken({secret}: {secret: string}): void
  }
}
like image 31
nshirley Avatar answered Oct 26 '22 02:10

nshirley