0
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.

TesterDick
  • 3,830
  • 5
  • 18

3 Answers3

3

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()

  })
})
TesterDick
  • 3,830
  • 5
  • 18
  • Thanks a lot man, you are a life saver was stuck on this problem for 4 days straight. For others who might later visit just make sure your viewport and visit function is inside beforeEach parameter – user20225195 Oct 19 '22 at 02:33
0

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')

agoff
  • 5,818
  • 1
  • 7
  • 20
  • Thanks for the response This is the message it is displaying me "Cannot read properties of undefined (reading 'username')" I am passing them like this signIn.SignInMethod(credentials.username, credentials.password) // validate account validateAccount.validateAccountMethod(credentials.vcode.toString()) – user20225195 Oct 18 '22 at 17:06
  • You would need to reference them like `Cypress.env('credentials').username` instead of just `credentials.username`. – agoff Oct 18 '22 at 17:29
  • Yes I tried that as well, but it's showing same message. "Cannot read properties of undefined (reading 'username')" As soon as my test starts to execute, this is displayed right at the beginning We are not using NewAccountCredentials in which we are storing string, which we were previously getting in my promise – user20225195 Oct 18 '22 at 17:38
  • I don't really follow - can you add your `it()` block where this is failing and any supporting functions? Preferably to your original post, so it can be formatted. – agoff Oct 18 '22 at 18:04
  • I have added the complete file for more visibility, please check – user20225195 Oct 18 '22 at 18:15
-1

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

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 21 '22 at 01:53