0

Full Typescript Cypress project.

I get the following error when trying to use the following custom command in this way:

Usage:

    cy.restGetUserId(userEmail).then(userId => {
        //do something with userId
    });

Custom command:

Cypress.Commands.add('restGetUserId', (userEmail) => {
    expect(userEmail).to.not.equal(undefined);

    cy.request({
        //some request, works!
    }).then((response) => {
        cy.wrap(response.body.id);
    });
});

Currently documented:

    /**
     * also works as a normal user
     *
     * @example cy.restGetUserId('some@email.com');
     * @param userEmail - get the userId from this email
     * @returns the id of the given email/user.
     */
    restGetUserId(userEmail: string): string;

My error is most likely in the documentation of this method, what is the recommended way to document this method? (especially the return value i would guess)

Bambi
  • 139
  • 8

2 Answers2

1

A custom command may not return anything other than Chainable<T>. So a valid type definition for you example may look like this:

   restGetUserId(userEmail: string): Chainable<string>;
Mikhail Bolotov
  • 976
  • 1
  • 6
  • 13
  • Thanks a lot! How would i write this in a case where more than one string will be returned? Can i document how these variables are called? I would like something along the lines of: `Chainable` – Bambi Jul 28 '22 at 11:14
  • 1
    No, it's not possible to define several types in a type argument directly. But you can try to define your own custom type `type MyType = { id: string, foo: boolean, foo2: string }` and use it as `Chainable` – Mikhail Bolotov Jul 28 '22 at 11:28
  • Great Advice! Where exactly would this type Definition need to be written? – Bambi Jul 28 '22 at 13:33
  • It does not need in runtime, so it can be placed anywhere your IDE will look for – Mikhail Bolotov Jul 28 '22 at 15:19
0

If you want to continue to use the something that is used or created within your custom command, you'll have to return the chain of cypress commands that yields the item.

For your case you'll have to do the following:

Cypress.Commands.add('restGetUserId', (userEmail) => {
    expect(userEmail).to.not.equal(undefined);

    return cy.request({
        //some request, works!
    }).its('response.body.id') // get the id we need
});

Now you'll have access to the id returned by the request.

cy.restGetUserId(userEmail).then(cy.log) //logs the id from request
jjhelguero
  • 2,281
  • 5
  • 13