Rayrun
← Back to Discord Forum

pass function by reference to page.evaluate/other?

wickynilliamsposted in #help-playwright
Open in Discord
wickynilliams
wickynilliams

i have some object available on window in my app. throughout tests i need to interact with this object, calling methods on it, using their return value etc. i can do this with page.evaluate:

await page.evaluate(() => {
  const result = window.obj.doSomething(1,2,3)
  window.obj.doSomethingElse(4,5,6, result)
})

but i'd like to provide a nicer/more succinct API via a fixture. ideally something like this:

await myFixture.do(obj => {
  const result = obj.doSomething(1,2,3)
  obj.doSomethingElse(4,5,6, result)
})

is there some way to achieve this kind of API? i've experimented with exposing bindings/functions but nothing quite works.

This thread is trying to answer question "Is there a way to provide a more succinct API via a fixture to interact with an object during tests?"

1 reply

That sounds like Page Object Model: https://playwright.dev/docs/pom

Answer

Sure, @playwright/test lets you create fixtures for a more succinct API to interact with objects during tests.

What are Fixtures?

Fixtures help set up the environment for each test. They handle setup and teardown in one place, making test writing easier.

Reusability

You can define a fixture once and reuse it across multiple tests. For example, you could create a TodoPage fixture and use it in all your tests.

On-Demand

Fixtures are on-demand. @playwright/test only sets up the fixtures needed by each test. So, you can define as many fixtures as you want without affecting other tests.

Composability

Fixtures are composable. They can depend on each other to provide complex behaviors. If you have multiple objects to interact with during your tests, you can create separate fixtures for each and compose them together.

import { test } from '@playwright/test';

test.describe('Todo tests', () => {
  test('should add a todo item', async ({ TodoPage }) => {
    await TodoPage.addTodo('Buy milk');
    // ...
  });

  test('should complete a todo item', async ({ TodoPage }) => {
    await TodoPage.completeTodo('Buy milk');
    // ...
  });
});

In this example, TodoPage is a fixture that provides a succinct API for interacting with the todo list on the page.

So, @playwright/test gives you the flexibility to create custom fixtures for a more succinct API to interact with objects during tests.

Related Discord Threads

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.