Reputation: 409
When automating a login for, I perform click on an element that it could lead to navigation to another page but in case of invalid password it will just display error message on the same page without actually causing a navigation.
I have tried:
await Promise.all([
this.page.submitButton.click(),
this.page.waitForNavigation()
]);
But it will fail for the case when no navigation happens. I was thinking about interception the response, to check if the login succeed/failed, but may be there is a more clear way to do so ?
Upvotes: 4
Views: 16929
Reputation: 95
Looks like you have two competing promises to await
for here - one for the error message to appear, and another one for navigation to happen.
Only one will initially resolve, hence we can use Promise.any
to avoid excessive waiting or code branching.
await submitButton.click({
noWaitAfter: true, // since we are handling potential navigation ourselves
});
// adding custom then callbacks to distinguish between the two
const navigationPromise = page.waitForURL('**').then(() => true);
const errorMessagePromise = messageLocator.isVisible().then(() => false);
const isLoggedIn = await Promise.any([
navigationPromise,
errorMessagePromise,
]);
// at this stage we have either new page loaded OR login form with error message displayed
See waitUntil
option of waitForURL
method for more precise control of page navigation event you are interested in.
Upvotes: 0
Reputation: 21607
I don't think you need some extra code besides this.page.submitButton.click()
.
The click function will wait for the navigation for you. So you could check after the click if your are in the same URL or not.
await this.page.submitButton.click(); // This will wait for a possible navigation
if(this.page.url() == destinationOnValidLogin) {
// Good login stuff
} else {
// Login failed
}
Upvotes: 1
Reputation: 1178
This code should give you an example of how to understand if you stay on the same page or navigate:
await this.page.submitButton.click();
try {
await this.page.waitForNavigation();
// if we are here it means login was successful
} catch(e) {
// if we are here it means login failed
}
Upvotes: 5