I am trying to do the following:
When I am on the cart page and click the CHECKOUT button, then there are 2 things that can happen:
I am redirected to the checkout page
I am asked sometimes to log in again => this is a bug in the app since I am already logged in but it asks me to log in again for some reason.
I need to write a Playwright test for the checkout process.
And in this test, I need to support that buggy behavior since there is no indication it will be resolved any time soon (or whatsoever).
This is what I got so far:
async clickCheckoutBtn() {
if (this.#isGuest) {
// redirects to the login page, so we don't have waitForURL like when we are logged in
await this.#checkoutBtn.click();
} else {
// TODO add here somehow to login again if required after clicking the checkout button
await Promise.all([
this.page.waitForResponse(
(response) =>
response.url().includes('/my-account/addressform') &&
response.status() === ResponseCode.SUCCESS
),
this.#checkoutBtn.click(),
this.page.waitForURL(/.*\/delivery-address\/add$/),
]);
}
}
Now, this is what I would like to do:
await page.getByRole('button').click();
if(await page.getByPlaceholder('login').isVisible()) {
await loginPage.login(username, password);
}
await page.waitForURL(/.*\/delivery-address\/add$/),
But in the case when I am redirected to the checkout I also need to waitForResponse of the /my-account/addressform
. (so after logging in I need to wait for it, but also after direct redirect to the checkout page, I need to wait for it as well)
So I would like to do this somehow inside the Promise.all
, but I don't how to do it.
Can you please help?
Yes you can do something like below using ternary operator.
Promises are future values which can be captured in variables and moved around in code asynchronously.
var p1 = page.getByRole('button').click();
var p2 = (await page.getByPlaceholder('login').isVisible()) ? loginPage.login(username, password) : Promise.resolve() //else empty promise which will resolve immediately
Promise.all([p1, p2]).then(results => {
await page.waitForURL(/.*\/delivery-address\/add$/)
});
More abstract version of it for general understanding:
var p1 = functionA();
var p2 = condition ? functionB() : Promise.resolve(); // or empty promise
Promise.all([p1, p2]).then(results => {
// code to handle results
});