A test signs a reader in to Shelf. It takes the email address from its test data and types it into the form. The form receives the word "undefined".
const reader = { name: "Ines", email: "ines@shelf.test", loans: 2 };
console.log(reader.Email);
console.log("Typing: " + reader.Email);
undefined
Typing: undefined
An object is a group of named values. Each named value is a property. This object has three: name, email and loans. You write a property as a name, a colon and a value.
A dot reads a property. reader.email gives the address.
The test asked for reader.Email, with a capital E. Property names are exact, so that is a different name. The object has no such property. JavaScript does not raise an error for that. It gives undefined, and the test continues with the wrong value.
That is the trap to remember. A misspelled property name is silent.
Objects inside objects, and other ways in
const reader = {
name: "Ines",
address: { city: "Porto", country: "Portugal" },
};
console.log(reader.address.city);
const field = "name";
console.log(reader[field]);
reader.name = "Ines M.";
reader.card = 1042;
console.log(reader.name);
console.log(reader.card);
Porto
Ines
Ines M.
1042
- A property can hold another object. Use one dot for each level.
- Square brackets read a property whose name is in a variable. Here
fieldholds"name". - Assigning to a property changes it.
- Assigning to a property that does not exist creates it.
reader was declared with const, and the last two changes still worked. const stops you giving the name reader a different object. It does not freeze what is inside the object.
Options objects
Framework calls often take an object as their last argument. It holds the options for the call.
page.getByRole('button', { name: 'Borrow' });
The second argument is an object with one property, name. Playwright uses it to find the button whose name is Borrow. An object keeps a call readable when there are several options, because each value has a label.
A shorter way to build test data
When a variable has the same name as the property you want, you can write the name once.
const name = "Ines";
const email = "ines@shelf.test";
const reader = { name, email };
console.log(reader.email);
ines@shelf.test
{ name, email } means the same as { name: name, email: email }. You will see it in most test data builders.
Remember this
An object groups values under exact names. A property that does not exist reads as undefined with no error. const protects the name, not the contents.
Reference: Working with objects in the MDN JavaScript Guide.