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.
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.
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);
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With