Hassan
Hassan

Reputation: 3

Cypress intercept

I am novice in automation and having a problem in cypress intercept method. I have to achieve following thing:

1- visit: https://opensource-demo.orangehrmlive.com 2- enter login credentials 3- on the click of l0gin button "I have to validate the entered username" through intercept method. Following is the my code

describe("cypressAssignment", ()=>{
it('Login a user and validate his name via intercept', ()=>{

    cy.intercept('POST', '/auth/login', (req) => {
        expect(req.body).to.include('Admin')
    }).as('username')
      
    cy.visit('https://opensource-demo.orangehrmlive.com')

    
    cy.get('form').within(($form)=>{
        cy.get('#divUsername').type('Admin')
        cy.get('#divPassword').type('admin123')

        cy.get('#btnLogin').click()

    })
  cy.wait('@username').its('response.body').should('to.have.property', 'name').and('include', 'Admin')

   

    cy.url().should('include','dashboard')
   

})

Upvotes: 0

Views: 1030

Answers (2)

Hassan
Hassan

Reputation: 3

This is what I done after your response @pavelsaman. Now I am getting ideas how to play with intercept:

describe("cypressAssignment", ()=>{
it('Login a user and validate his name via intercept', ()=>{

    cy.intercept('POST','**/auth/validateCredentials', (request) => { expect(request.body).to.include('txtUsername=Admin')
    })

    cy.visit('/')
    
    cy.get('form').within(($form)=>{
        cy.get('#txtUsername').type('Admin')
        cy.get('#txtPassword').type('admin123')
        cy.get('#btnLogin').click()

    })
})

Upvotes: 0

pavelsaman
pavelsaman

Reputation: 8352

I'd go for something like this. )Updated based on additional information in the comment section.)

it('SO Answer', () => {
    cy
      .visit('/');

    cy
      .intercept('POST', '**/auth/validateCredentials')
      .as('loginRoute');

    cy
      .get('#txtUsername')
      .type('Admin');

    cy
      .get('#txtPassword')
      .type('admin123');

    cy
      .get('#btnLogin')
      .click();

    cy
      .wait('@loginRoute')
      .its('request.body')
      .should('include', 'txtUsername=Admin');
});

To see the whole test case in the Test Runner:

enter image description here

The app renders HTML on the server side, so the response to the login action is a 302 redirection to /index.php/dashboard and a complete HTML sent in the response, so you can't check any username in the response in this case.

Upvotes: 1

Related Questions