I'm converting a bunch of tests from Selenium + Jest to Playwright + Jest, and one of the differences is that for element lookups, await page.$(".whatever") doesn't reject if it doesn't find the element.
I'm doing a lot of element lookups as we've built out Page Object Models for a lot of components.
My question is, do I need to manually add some error handling, or am I missing something here? Jest will tell me which test fails but there's no stack trace so it can be hard to track down what went wrong. Also, is this a good way to do it?
// some-test.js
it("should display the event title", async () => {
let eventTitle = await this.bookingPage.getEventTitle();
expect(await eventTitle.textContent()).toBe("Some special event");
});
// Page Object Model
class BookingPage extends PageObjectModel {
async getEventTitle() {
const selector = "h2.title .content";
const result = await page.$(selector);
if (!result) throw new Error(`Could not find selector: "${selector}"`);
return result;
}
}
If it is a good approach it seems like a pain to have to do for all lookups. Would it be a good idea to wrap page.$ in another function that just does it for me? It would be a bad idea to mutate page.$ itself right? So maybe create a wrapper method that does the error handling and it and then calls page.$?
So I could do something like this:
class PageObjectModel {
async $(selector) {
const result = await page.$(selector);
if (!result) throw new Error(`Could not find selector: "${selector}"`);
return result;
}
}
class BookingPage extends PageObjectModel {
async getEventTitle() {
return this.$("h2.title .content");
}
}
Which is kinda nice but then for some reason the stack trace only links to some-test.js and PageObjectModel.js, and not to BookingPage.js.
I feel like I'm not missing something about JS error handling in general? ¯_(ツ)_/¯