
const { test, expect } = require('@playwright/test');
const url = 'https://www.codexcity.com/2026/10/28/javascript-tutorial-exercise-14executable/';
const testCases = [
{ id: 'TC01', age: '18', license: 'Yes', allowed: true },
{ id: 'TC02', age: '17', license: 'Yes', allowed: false },
{ id: 'TC03', age: '19', license: 'Yes', allowed: true },
{ id: 'TC04', age: '18', license: 'No', allowed: false },
{ id: 'TC05', age: '17', license: 'No', allowed: false },
{ id: 'TC06', age: '25', license: 'Yes', allowed: true },
{ id: 'TC07', age: 'abc', license: 'Yes', allowed: false },
{ id: 'TC08', age: '18', license: 'YES', allowed: true },
{ id: 'TC09', age: '18', license: 'yes', allowed: true },
{ id: 'TC10', age: '18', license: 'yEs', allowed: true },
{ id: 'TC11', age: '0', license: 'Yes', allowed: false },
{ id: 'TC12', age: '-1', license: 'Yes', allowed: false }
];
test.describe('Exercise 14 - Car Rental Eligibility', () => {
for (const tc of testCases) {
test(`${tc.id}: Age ${tc.age}, License ${tc.license}`, async ({ page }) => {
let promptCount = 0;
let alertMessage = '';
page.on('dialog', async dialog => {
if (dialog.type() === 'prompt') {
promptCount++;
if (promptCount === 1) {
await dialog.accept(tc.age);
} else {
await dialog.accept(tc.license);
}
}
if (dialog.type() === 'alert') {
alertMessage = dialog.message();
await dialog.accept();
}
});
await page.goto(url);
await page.getByRole('button', {
name: 'Test',
exact: true
}).click();
const expectedMessage = tc.allowed
? 'You can rent a car!'
: 'You cannot rent a car. Lack of required documents / underage.';
expect(alertMessage).toBe(expectedMessage);
expect(promptCount).toBe(2);
});
}
});
In this Playwright tutorial, we will automate the testing of a JavaScript application that determines whether someone is eligible to rent a car based on their age and driving license.
In the previous JavaScript Tutorial Exercise 14, we developed a simple application that asks the user two questions:
- How old are you?
- Do you have a driving license?
The application evaluates the answers and displays a message indicating whether the user is allowed to rent a car.
Now we will take this exercise one step further by introducing automated software testing with Playwright.
Instead of manually entering different ages and driving license information, we will create an automated test suite that executes 12 different test scenarios.
Along the way, we will explore several important software testing concepts, including data driven testing, boundary value analysis, equivalence partitioning, test assertions and browser dialog handling.
1. Understanding the Application Under Test
Before developing automated tests, we need to understand the application’s expected behavior.
The original JavaScript application contains the following code:
function test() {
const minAge = 18;
const age = parseInt(prompt("Enter your age:"));
const hasLicense = prompt("Do you have a driving license? (Yes/No)").toLowerCase() === "yes";
if (age >= minAge && hasLicense) {
alert("You can rent a car!");
} else {
alert("You cannot rent a car. Lack of required documents / underage.");
}
}
The application uses two conditions to determine whether someone can rent a car.
The person must be at least 18 years old and must possess a driving license.
Both conditions must be satisfied.
The JavaScript logical AND operator (&&) evaluates whether both expressions are true.
If both conditions are satisfied, the application displays:
You can rent a car!
Otherwise, it displays:
You cannot rent a car. Lack of required documents / underage.
Our objective is to verify that the application behaves correctly for different combinations of input values.
2. Designing the Test Cases
Before writing the Playwright code, we should identify the scenarios we want to test.
We will create 12 test cases.
| Test ID | Age | Driving License | Expected Result |
|---|---|---|---|
| TC01 | 18 | Yes | Allowed |
| TC02 | 17 | Yes | Denied |
| TC03 | 19 | Yes | Allowed |
| TC04 | 18 | No | Denied |
| TC05 | 17 | No | Denied |
| TC06 | 25 | Yes | Allowed |
| TC07 | abc | Yes | Denied |
| TC08 | 18 | YES | Allowed |
| TC09 | 18 | yes | Allowed |
| TC10 | 18 | yEs | Allowed |
| TC11 | 0 | Yes | Denied |
| TC12 | -1 | Yes | Denied |
These test cases cover several different aspects of the application’s functionality.
Boundary Value Analysis
Boundary value analysis is a software testing technique that focuses on values at and around the boundaries of valid input ranges.
The minimum rental age is 18.
Therefore, three particularly interesting test values are:
- 17: Immediately below the minimum age
- 18: Exactly at the minimum age
- 19: Immediately above the minimum age
These values are covered by TC01, TC02 and TC03.
Boundary value analysis is useful because software defects frequently occur around boundaries.
For example, a developer might accidentally use the greater than operator (>) instead of the greater than or equal to operator (>=).
Such a mistake would incorrectly reject someone who is exactly 18 years old.
Equivalence Partitioning
Equivalence partitioning divides input data into groups that are expected to behave similarly.
For the age input, we can identify three useful partitions:
- Valid ages below 18
- Valid ages of 18 or above
- Invalid age inputs
Instead of testing every possible age, we select representative values from these partitions.
For example, TC06 verifies that a 25 year old with a driving license is eligible, while TC07 verifies how the application handles a nonnumeric input.
Case Insensitivity
The application uses the JavaScript toLowerCase() method when evaluating the driving license answer.
This means that the following inputs should produce the same result:
Yes
YES
yes
yEs
Test cases TC08, TC09 and TC10 verify that the application correctly handles different capitalizations.
3. Creating the Playwright Test Suite
We will use Playwright, a browser automation and end to end testing framework.
The test suite is written in JavaScript using the Playwright Test framework.
Here is the complete implementation:
const { test, expect } = require('@playwright/test');
const url = 'https://www.codexcity.com/2026/10/28/javascript-tutorial-exercise-14executable/';
const testCases = [
{ id: 'TC01', age: '18', license: 'Yes', allowed: true },
{ id: 'TC02', age: '17', license: 'Yes', allowed: false },
{ id: 'TC03', age: '19', license: 'Yes', allowed: true },
{ id: 'TC04', age: '18', license: 'No', allowed: false },
{ id: 'TC05', age: '17', license: 'No', allowed: false },
{ id: 'TC06', age: '25', license: 'Yes', allowed: true },
{ id: 'TC07', age: 'abc', license: 'Yes', allowed: false },
{ id: 'TC08', age: '18', license: 'YES', allowed: true },
{ id: 'TC09', age: '18', license: 'yes', allowed: true },
{ id: 'TC10', age: '18', license: 'yEs', allowed: true },
{ id: 'TC11', age: '0', license: 'Yes', allowed: false },
{ id: 'TC12', age: '-1', license: 'Yes', allowed: false }
];
test.describe('Exercise 14 - Car Rental Eligibility', () => {
for (const tc of testCases) {
test(`${tc.id}: Age ${tc.age}, License ${tc.license}`, async ({ page }) => {
let promptCount = 0;
let alertMessage = '';
page.on('dialog', async dialog => {
if (dialog.type() === 'prompt') {
promptCount++;
if (promptCount === 1) {
await dialog.accept(tc.age);
} else {
await dialog.accept(tc.license);
}
}
if (dialog.type() === 'alert') {
alertMessage = dialog.message();
await dialog.accept();
}
});
await page.goto(url);
await page.getByRole('button', {
name: 'Test',
exact: true
}).click();
const expectedMessage = tc.allowed
? 'You can rent a car!'
: 'You cannot rent a car. Lack of required documents / underage.';
expect(alertMessage).toBe(expectedMessage);
expect(promptCount).toBe(2);
});
}
});
Let’s examine the different components of this test suite.
4. Importing Playwright
The first line imports two important components from Playwright:
const { test, expect } = require('@playwright/test');
The test function allows us to define automated test cases.
The expect function provides assertions that verify whether the actual results match the expected results.
An assertion is an essential part of automated testing because it determines whether a test passes or fails.
Without assertions, a script might interact with an application without verifying that the application behaves correctly.
5. Defining the Application URL
Next, we define the URL of the application we want to test.
const url = 'https://www.codexcity.com/2026/10/28/javascript-tutorial-exercise-14executable/';
By storing the URL in a constant, we avoid repeating it throughout the test suite.
If the application moves to another location, we only need to update this value.
This improves maintainability.
6. Introducing Data Driven Testing
One of the most important concepts in this exercise is data driven testing.
Instead of writing 12 separate test functions, we define an array containing the input data and expected results.
const testCases = [
{ id: 'TC01', age: '18', license: 'Yes', allowed: true },
{ id: 'TC02', age: '17', license: 'Yes', allowed: false },
{ id: 'TC03', age: '19', license: 'Yes', allowed: true }
];
Each object represents one test case.
The properties have the following meanings:
| Property | Description |
|---|---|
id | Unique identifier for the test case |
age | Age entered in the first browser prompt |
license | Driving license answer entered in the second prompt |
allowed | Expected eligibility result |
Notice that the age values are stored as strings.
This is intentional.
The browser’s prompt() function returns text, and Playwright’s dialog.accept() method accepts a string as input.
The application itself is responsible for converting the age into a number using parseInt().
This allows us to test invalid input such as abc.
Why Use Data Driven Testing?
Imagine that we want to add another 50 test scenarios.
Without data driven testing, we might need to write 50 additional test functions.
With our approach, we only need to add more objects to the testCases array.
The existing test logic can be reused.
This reduces code duplication and makes the test suite easier to maintain.
7. Grouping Tests with test.describe()
Playwright provides the test.describe() function to organize related tests.
test.describe('Exercise 14 - Car Rental Eligibility', () => {
// Test cases
});
All tests inside this block belong to the same logical group.
This is particularly useful when a project contains multiple applications, exercises or functional areas.
For example, we could create separate groups for login functionality, user registration, payment processing and car rental eligibility.
8. Generating Tests Dynamically
The next interesting part is the for...of loop.
for (const tc of testCases) {
test(`${tc.id}: Age ${tc.age}, License ${tc.license}`, async ({ page }) => {
// Test implementation
});
}
The loop iterates through every object in the testCases array.
For each object, Playwright registers a separate test.
The test title is generated dynamically using a JavaScript template literal.
For example:
TC01: Age 18, License Yes
TC02: Age 17, License Yes
TC03: Age 19, License Yes
This approach provides two important advantages.
First, every test case appears individually in the Playwright test report.
Second, when a test fails, we can immediately identify which combination of input values caused the failure.
Although the tests share the same implementation, Playwright treats them as separate test cases.
Each test receives its own isolated browser page through the page fixture.
9. Handling JavaScript Browser Dialogs
Our application uses two JavaScript prompt() dialogs and one alert() dialog.
These dialogs require special handling in Playwright.
Unlike ordinary HTML input elements, native JavaScript dialogs cannot be manipulated using standard page locators.
Instead, Playwright provides a dialog event.
page.on('dialog', async dialog => {
// Handle browser dialogs
});
The event listener is registered before clicking the Test button.
This is important because the dialogs appear immediately when the application executes.
Handling the First and Second Prompts
We use a counter to distinguish between the two prompts.
let promptCount = 0;
Whenever Playwright detects a prompt, we increment the counter.
if (dialog.type() === 'prompt') {
promptCount++;
if (promptCount === 1) {
await dialog.accept(tc.age);
} else {
await dialog.accept(tc.license);
}
}
The first prompt receives the age.
The second prompt receives the driving license answer.
For TC01, Playwright automatically enters:
First prompt: 18
Second prompt: Yes
The dialog.accept() method simulates entering the specified value and confirming the dialog.
This is a useful technique for testing applications that rely on native JavaScript browser dialogs.
Handling the Alert Dialog
After processing the input values, the application displays an alert.
We capture its message:
if (dialog.type() === 'alert') {
alertMessage = dialog.message();
await dialog.accept();
}
The dialog.message() method retrieves the text displayed in the alert.
We store this text in the alertMessage variable so that we can verify it later.
The dialog.accept() method closes the alert.
It is important to handle these dialogs because an unhandled dialog can prevent the application from continuing.
10. Navigating to the Application
The following instruction opens the application in the browser:
await page.goto(url);
The page object is provided by Playwright.
It represents a browser tab and provides methods for navigation, interacting with elements and inspecting the page.
The await keyword ensures that the navigation operation completes before the test continues.
11. Clicking the Test Button
Once the application is loaded, we need to execute the JavaScript function.
We do this by clicking the Test button.
await page.getByRole('button', {
name: 'Test',
exact: true
}).click();
The getByRole() method locates an element using its accessible role and name.
In this case, we search for a button whose accessible name is exactly Test.
The exact: true option prevents Playwright from matching other buttons with similar names, such as Test Again.
Using accessible roles is generally preferable to relying on fragile CSS selectors because it reflects how users and assistive technologies identify interface elements.
12. Determining the Expected Result
After the application has executed, we need to determine which message should have appeared.
We use the JavaScript conditional operator:
const expectedMessage = tc.allowed
? 'You can rent a car!'
: 'You cannot rent a car. Lack of required documents / underage.';
This is also known as the ternary operator.
It has the following structure:
condition ? valueIfTrue : valueIfFalse;
If tc.allowed is true, the expected message indicates that the person can rent a car.
Otherwise, the expected message indicates that the person cannot rent a car.
The expected result comes from our predefined test data rather than being calculated using the application’s own eligibility logic.
This separation is important because the automated test must independently verify the application’s behavior.
13. Verifying the Results with Assertions
The final part of each test contains two assertions.
expect(alertMessage).toBe(expectedMessage);
expect(promptCount).toBe(2);
First Assertion: Verify the Alert Message
expect(alertMessage).toBe(expectedMessage);
This assertion compares the actual alert message with the expected message.
For TC01, the expected result is:
You can rent a car!
If the application displays this exact message, the assertion passes.
If the application displays something different, the assertion fails.
The toBe() matcher performs a strict equality comparison.
This means that differences in capitalization, punctuation or whitespace can cause the test to fail.
Second Assertion: Verify the Number of Prompts
expect(promptCount).toBe(2);
This assertion verifies that the application displayed exactly two prompt dialogs.
Why is this useful?
Imagine that a developer accidentally removes the driving license question.
The application might still display an eligibility message, but the expected interaction sequence would be incorrect.
By verifying the number of prompts, we check another aspect of the application’s behavior.
This demonstrates an important testing principle: a test should verify more than just the final output when intermediate behavior is also part of the requirements.
One limitation is that counting prompts does not verify their exact wording or order. Those could be checked with additional assertions.
14. Executing the Test Suite
Assuming Playwright is already installed and configured, save the code in a file named:
exercise14.spec.js
We can execute the test suite using the following command:
npx playwright test exercise14.spec.js
Playwright discovers the 12 test cases and executes them.
If the application behaves as expected, all 12 tests should pass.
A successful test run might produce output similar to:
Running 12 tests using 1 worker
✓ TC01: Age 18, License Yes
✓ TC02: Age 17, License Yes
✓ TC03: Age 19, License Yes
✓ TC04: Age 18, License No
✓ TC05: Age 17, License No
✓ TC06: Age 25, License Yes
✓ TC07: Age abc, License Yes
✓ TC08: Age 18, License YES
✓ TC09: Age 18, License yes
✓ TC10: Age 18, License yEs
✓ TC11: Age 0, License Yes
✓ TC12: Age -1, License Yes
12 passed
This output is illustrative rather than the result of an actual test execution.
The number of workers and the output format depend on the Playwright configuration.
To execute the tests in a visible browser, use:
npx playwright test exercise14.spec.js --headed
To inspect the HTML test report, use:
npx playwright show-report
The HTML report provides information about individual test results, execution times and failures.
15. What Happens When a Test Fails?
One of the main advantages of automated testing is the ability to detect regressions.
A regression occurs when a change to the application introduces a defect in functionality that previously worked.
Imagine that a developer accidentally changes the following condition:
if (age >= minAge && hasLicense)
To:
if (age > minAge && hasLicense)
The application now requires users to be older than 18 instead of at least 18.
Our test case TC01 would detect this defect.
The expected result for an 18 year old with a driving license is:
You can rent a car!
However, the modified application would display:
You cannot rent a car. Lack of required documents / underage.
The assertion would fail, and Playwright would report the mismatch.
This illustrates how automated regression testing helps developers identify unintended changes in application behavior.
16. Possible Improvements to the Test Suite
Our test suite already covers several important scenarios, but it can be expanded.
For example, we could add tests for empty input values, decimal ages, leading and trailing whitespace, and unexpected driving license responses.
There is also an interesting issue with the application’s use of parseInt().
Consider the following input:
parseInt("18abc");
JavaScript returns:
18
This means that the application would accept 18abc as a valid age of 18.
Similarly:
parseInt("18.9");
Returns:
18
Whether this behavior is acceptable depends on the application’s requirements.
From a software testing perspective, these are interesting additional test scenarios because they reveal how the application handles malformed input.
We could also improve the test implementation by verifying that exactly one alert appears and by checking the text of both prompts.
For a larger application, we might introduce reusable helper functions or Page Object Models to improve maintainability.
17. Connecting Playwright with Software Testing Principles
This exercise demonstrates how programming and software testing complement each other.
We started with a simple JavaScript application and transformed its functional requirements into automated test cases.
Several concepts commonly encountered in professional software testing are demonstrated here.
Test design techniques: Boundary value analysis and equivalence partitioning help us select meaningful test inputs.
Test automation: Playwright automatically interacts with the application and verifies its behavior.
Data driven testing: A single reusable test implementation executes multiple scenarios.
Assertions: Expected results are compared with actual results to determine whether tests pass or fail.
Regression testing: The same tests can be executed after application changes to detect unintended defects.
Test maintainability: Separating test data from test logic makes it easier to extend the test suite.
These concepts are also relevant to the ISTQB Foundation Level syllabus and to practical software quality assurance work.
Conclusion
In this tutorial, we created a Playwright test suite containing 12 automated test cases for a JavaScript car rental eligibility application.
We learned how to handle native JavaScript prompts and alerts, generate tests dynamically from an array, verify application behavior using assertions and apply established software testing techniques.
The most important lesson is that automated testing is not simply about making a browser click buttons. It is about designing meaningful test scenarios, defining expected results and verifying that the application meets its requirements.
By combining JavaScript programming exercises with Playwright automation, we can develop both software development and software testing skills.
This is a practical foundation for more advanced topics such as automated regression testing, continuous integration and end to end testing of web applications.
Try the original application: JavaScript Tutorial Exercise 14: Car Rental Eligibility
Technologies used: JavaScript, Node.js, Playwright Test
Software testing techniques: Boundary Value Analysis, Equivalence Partitioning, Data Driven Testing, Functional Testing, Regression Testing