A new tester copies a Playwright test and tidies the first line. They remove the curly brackets around page, because the brackets look like noise.
import { test } from '@playwright/test';
test('a reader can borrow a book', async (page) => {
await page.goto('/books');
});
The test no longer works. Playwright refuses to run it, and its error says the first argument must use the object destructuring pattern.
To see why, here is a small runner that does what Playwright does. It builds one object and passes that object to your callback.
function runTest(body) {
const fixtures = { page: "the page", request: "the request" };
body(fixtures);
}
runTest((page) => {
console.log(typeof page);
});
runTest(({ page }) => {
console.log(typeof page);
});
object
string
The runner always passes the whole object. In the first test, the parameter page is only a name for that whole object. In the second test, the braces take the page property out of it.
Taking named properties out of an object is called destructuring. In Playwright, the properties of that object are called fixtures. A fixture is something the runner prepares for your test, such as a browser page.
Destructuring an object
You can use the same braces in a normal line of code.
const reader = { name: "Ines", email: "ines@shelf.test", loans: 2 };
const { name, loans } = reader;
console.log(name);
console.log(loans);
const { card } = reader;
console.log(card);
Ines
2
undefined
const { name, loans } = reader creates two variables. Each one gets the property with the same name.
The names must match the property names exactly. reader has no card property, so card is undefined. There is no error, the same as when you read a missing property with a dot.
Two additions are useful in test code:
const reader = { name: "Ines" };
const { name: readerName, loans = 0 } = reader;
console.log(readerName);
console.log(loans);
Ines
0
name: readerName takes the name property and calls the variable readerName. loans = 0 gives a default for a property that is missing.
Destructuring an array
Square brackets do the same for a list. They go by position, not by name.
const [first, second] = ["Dune", "Emma", "Ulysses"];
console.log(first);
console.log(second);
Dune
Emma
Back to the test
A Playwright test can take more than one fixture. List the ones you need inside the braces.
import { test } from '@playwright/test';
test('the loans list matches the API', async ({ page, request }) => {
// page drives the browser, request calls the API
});
When a failure says page is not what you expected, look at the first line of the test before anything else.
Remember this
Braces in a parameter list take named properties from the object that is passed in. The names must match exactly. A name that matches nothing is undefined.
Reference: Destructuring on MDN.