Home > Mobile >  How to refractor promise code for cypress
How to refractor promise code for cypress

Time:10-19

import SignInPage from '../pages/signInPage.cy'
import ValidateAccountPage from '../pages/validateAccountPage.cy'
import DeptPage from '../pages/deptPage.cy'
import HomePage from '../pages/homePage.cy'
import DeleteAccount from '../pages/deleteAccount.cy'

type NewAccountCredentials = { username: string, password: string, vcode: number, uid: string };

const URLS = {
    remote: {
        client: "http://54.39.177.218:8080",
        server: "http://54.39.177.218:3020/api/v2"
    }
}

const urlTarget = "remote";

const clientUrl = URLS[urlTarget].client;
const serverUrl = URLS[urlTarget].server;

const signIn = new SignInPage()
const validateAccount = new ValidateAccountPage()
const deptPage = new DeptPage()
const homePage = new HomePage()
const deleteAccount = new DeleteAccount()





describe('Smoke test', () => {



    let value
    let credentials

    beforeEach(async () => {


        cy.fixture('addDebtDetails').then(function (data) {

            value = data

        })

        cy.viewport(390, 844);
        // create a new non-validated account in the back-end
        credentials = await new Promise<NewAccountCredentials>((resolve, reject) => {
            cy.request(serverUrl   '/test-accounts/free').then(response => {
                expect(response.body).to.have.property("username");
                resolve(response.body);
            })
        });



        // load the app - should default to the sign-in page

        cy.visit(clientUrl, {
            onBeforeLoad: (win) => {
                win.sessionStorage.clear();
                win.localStorage.clear();
            }
        });


    })
    it('verifying home page before debts have been added', async () => {


        // sign-in
        signIn.SignInMethod(credentials.username, credentials.password)

        // validate account
        validateAccount.validateAccountMethod(credentials.vcode.toString())

        // verify that we are on the home page and see the correct greeting and workspace name

        homePage.HomePageMethod()





        /* CLEANUP AFTER EACH TEST */
        deleteAccount.DeleteAccountMethod(credentials.password)

        // must always delete the created account even if any of the above testing fails
        await new Promise<void>((resolve, reject) => {
            cy.request("DELETE", `${serverUrl}/test-accounts/uid/${credentials.uid}`).then(response => {
                expect(response.status).to.be.equal(200);
                resolve();
            })
        });

    })

    it('verifying debt page  after debt is added', async () => {

        /* BEFORE EACH TEST */



        // sign-in
        signIn.SignInMethod(credentials.username, credentials.password)

        // validate account
        validateAccount.validateAccountMethod(credentials.vcode.toString())
        cy.wait(2000)
        // verify that we are on the home page and see the correct greeting and workspace name

        deptPage.AddDeptMethod(value.nickName, value.currentBalance, value.annualPercentageRate, value.minimumPayment)

        deptPage.AddCalenderDetails(value.calenderYear, value.calenderMonth, value.calenderMonthAndDay)

        homePage.HomePageMethodAfterDebt()

        /* CLEANUP AFTER EACH TEST */
        deleteAccount.DeleteAccountMethod(credentials.password)

        // must always delete the created account even if any of the above testing fails
        await new Promise<void>((resolve, reject) => {
            cy.request("DELETE", `${serverUrl}/test-accounts/uid/${credentials.uid}`).then(response => {
                expect(response.status).to.be.equal(200);
                resolve();
            })
        });

    })
})

As cypress is asynchronous, my code contains a promise which is failing to get the request because of timeout, how can I delay the request. How to apply promise on this code as per cypress documentation. I have now added the completed file for further clarification, please check it. Can you please check now by running this.

CodePudding user response:

Because Cypress commands are already asynchronous, you don't need the Promise at all. Instead, you can store variables in a number of ways, my personal favorite being Cypress environment variables.

...
beforeEach(() => {
  cy.request(serverUrl   '/test-accounts/free').then(response => {
     expect(response.body).to.have.property("username");
     Cypress.env('credentials', response.body);
  })
  cy.visit(clientUrl, {
     onBeforeLoad: (win) => {
       win.sessionStorage.clear();
       win.localStorage.clear();
     }
  });
});

In the above, you could then reference those credentials via Cypress.env('credentials')

CodePudding user response:

Cypress automatically waits for all commands in the beforeEach() to finish before running the it() block, so you don't need any Promises.

If you have concerns about credentials, repeat the check for property "username" at the top of each test:

expect(credentials).to.have.property('username');

The same applies to your cleanup code, if you move it into afterEach() there is no need for the Promise in that section.

Full test

describe('Smoke test', () => {

  let value
  let credentials

  beforeEach(() => {
    cy.fixture('addDebtDetails')
      .then((data) => value = data)

    // create a new non-validated account in the back-end
    cy.request(serverUrl   '/test-accounts/free')
      .then(response => {
        expect(response.body).to.have.property("username");
        credentials = response.body;
      })
    });

    // load the app - should default to the sign-in page
    cy.viewport(390, 844);
    cy.visit(clientUrl, {
      onBeforeLoad: (win) => {
        win.sessionStorage.clear();
        win.localStorage.clear();
      }
    });
  })

  afterEach(() => {
    /* CLEANUP AFTER EACH TEST */
    deleteAccount.DeleteAccountMethod(credentials.password)

    // must always delete the created account even if any of the above testing fails
    cy.request("DELETE", `${serverUrl}/test-accounts/uid/${credentials.uid}`)
      .then(response => {
        expect(response.status).to.be.equal(200);
      })
  })

  it('verifying home page before debts have been added', () => {

    // same check as above, should still be passing
    expect(credentials).to.have.property('username');   

    // sign-in
    signIn.SignInMethod(credentials.username, credentials.password)

    // validate account
    validateAccount.validateAccountMethod(credentials.vcode.toString())

    // verify that we are on the home page...
    homePage.HomePageMethod()

  })

  it('verifying debt page  after debt is added', () => {

    // same check as above, should still be passing
    expect(credentials).to.have.property('username');   

    // sign-in
    signIn.SignInMethod(credentials.username, credentials.password)

    // validate account
    validateAccount.validateAccountMethod(credentials.vcode.toString())

    // verify that we are on the dept page...
    deptPage.AddDeptMethod(value.nickName, value.currentBalance, value.annualPercentageRate, value.minimumPayment)
    deptPage.AddCalenderDetails(value.calenderYear, value.calenderMonth, value.calenderMonthAndDay)

    homePage.HomePageMethodAfterDebt()

  })
})

CodePudding user response:

you can set in package.json jest timeOut. "jest": { "testTimeout": 15000, }

  • Related