How do you create a dynamic goto function in Playwright?
If you've ever needed create a goto
method that is dynamic in that it can take parameters and use them in the URL you want to visit, this solution should be helpful. I don't have a demo site to write live code against for this example, so we're just going to be working with sudo code.
For this example assume you have a url that allows you to both register by visiting the page direct /auth/register
or also allows a URL parameters for /auth/register?invitation=xxxxxx
to be passed into the url that allows you to land on an pre-filled page to register.
In the below example when we goto(inviteId)
we dynamically build the url with the passed in invitation Id.
// /tests/auth/register.spec.ts
import { RegisterPage } from "@pages";
import { getInvitationId } from "@datafactory";
import { test } from "@playwright/test";
test.describe("Register Specs", () => {
let inviteId;
test.beforeEach(async () => {
inviteId = await getInvitationId();
});
test("Register with existing Invite Id", async ({ page }) => {
const registerPage = new RegisterPage(page);
await registerPage.goto(inviteId);
// Add additional assertions
});
});
// /lib/pages/registerPage.ts
export class RegisterPage {
async goto(inviteId?) {
let url = "/auth/register";
if (inviteId) url += "?invitation=" + inviteId;
await this.page.goto(url);
}
constructor(private readonly page: Page) {}
}
Thanks for reading! If you found this helpful, reach out and let me know on LinkedIn or consider buying me a cup of coffee. If you want more content delivered to you in your inbox subscribe below, and be sure to leave a ❤️ to show some love.