I'm having trouble getting custom error messages to work with driver.wait()
in selenium (+ cucumber). The definition is driver.wait(condition, timeout, message)
where
- condition is something like
until.elementLocated(By.css('.myClass'))
- timeout is in ms
- message is "An optional message to use if the wait times out."
More info here under this.wait()
.
As far as I understand it, the point of the api is that you can pass a timeout period and a message to use if the timeout period expires without the condition being true.
With that in mind, I defined a function locateElementWithTimeout
that takes
- the driver
- a locator (something like
By.css(".myClass")
) - a timeout value (something like
5000
) - a timeoutMessage (something like "my timeout message")
async function locateElementWithTimeout(driver, by, timeout, timeoutMessage) {
// need to split into 2 as we use timeout twice
const timeoutInHalf = Math.floor(timeout / 2);
const element = await driver.wait(until.elementLocated(by), timeoutInHalf, timeoutMessage);
await driver.wait(until.elementIsVisible(element), timeoutInHalf, timeoutMessage);
return element;
}
And I also defined a function typeInWithTimeout
async function typeInWithTimeout(driver, by, timeout, timeoutMessage, textToType) {
const element = await locateElementWithTimeout(driver, by, timeout,
`Unable to locate element for typing text - ${timeoutMessage}`);
// bridge is needed for anything apart from firefox
const actions = driver.actions({ bridge: true });
await actions.click(element).sendKeys(textToType).perform();
}
called like
await typeInWithTimeout(driver, By.id("login_box"), 5000, 'Unable to locate login box', "myUsername");
Previously in my code (~1 second of execution earlier) I called the following function to define timeouts:
await driver.manage().setTimeouts({
implicit: 50 * 1000,
pageLoad: 50 * 1000,
script: 50 * 1000,
});
So now to my problem. I'm testing the failure condition by trying to locate an element that doesn't exist, with the expectation that it throws an error with the message
that I defined. My problem is that instead of waiting the 5 seconds that I requested in the function call, selenium instead waits for the full 50 seconds and then fails with Error: function timed out, ensure the promise resolves within 50000 milliseconds
. Why doesn't it fail in the 5 seconds that I requested?