aviya.developer
aviya.developer

Reputation: 3613

Is it possible to return or await for return of cypress intercept?

I would like to get the response of an intercept cypress call while running an e2e test:

const registerUser = async (username, password)=>{
    cy.visit('<user_registration_url');
    
    cy.intercept('/registration').as('registration');
    
    
    cy.get('input#username').type(username);
    cy.get('input#password').type(password);
    cy.get('button#submit').click()
    
    // Expected response:
    //{statusCode: 200, body: {userId: <string>}}
    const result = await cy.wait('@registration');
    const userId = result.response.body.userId;
    return userId

it('should test something with a newly registered user', ()=>{
    const userId = registerUser('foobar', 'password');
    // ... keep testing using the userId which was generated on the backend.
});

Upvotes: 1

Views: 821

Answers (2)

aviya.developer
aviya.developer

Reputation: 3613

So indeed as @pavelsman mentioned there is no async/await syntax for cypress. In order to make utility functions one can return a chainable as in this example:

const registerUser = (username, password)=>{
    cy.visit('<user_registration_url');
    
    cy.intercept('/registration').as('registration');
    
    
    cy.get('input#username').type(username);
    cy.get('input#password').type(password);
    cy.get('button#submit').click()
    
    // Expected response:
    //{statusCode: 200, body: {userId: <string>}}
    return cy.wait('@registration');


it('should test something with a newly registered user', ()=>{
    registerUser('foobar', 'password').then(result=>{
        const userId = result.response.body.userId;
        // ... keep testing using the userId which was generated on the backend.
    });
});

Upvotes: 0

pavelsaman
pavelsaman

Reputation: 8362

No, this won't work.

Cypress is asynchronous, so the commands won't return any data that you can assign to variables. You can read more on then in Cypress docs.

You can get to the response like so:

cy
  .wait('@registration')
  .then(response => {
    // some other code
  });

or you can check e.g. a status code like so:

cy
  .wait('@registration')
  .its('response.statusCode')
  .should('eq', 201);

You can see many examples on the page for cy.intercept command.

Upvotes: 1

Related Questions