What is a callback function in JavaScript?
Written by Jatin Thacker, Automation Architect · Updated
map(), and others run later, when an event happens or slow work finishes.This answer is one piece of Chapter 6: Async and Await.
- Error Handling & Debugging
- Callbacks & Promises
- Async/Await Mastery
- Practice and interview questions: Asynchronous JavaScript & Modern ES6+
You hand a function over and let someone else decide when to run it. That is all a callback is, and test code is full of them: the function you give test(), the arrow function inside map(), and the handler you give page.on().
The example uses the last kind. A browser alert stops the page until someone answers it, and by default Playwright dismisses dialogs for you. To see what the alert said, the test passes a callback to page.on('dialog', ...). Playwright keeps that function and calls it when a dialog opens, passing in the dialog object.
Order matters. The callback is registered first, before the click on Archive delivered. When the click opens the alert, Playwright runs the callback, which records dialog.message() and then accepts the dialog. Afterwards, messages holds Archiving is disabled in the practice environment., and the assertion checks it.
The callback must deal with the dialog. One that only logs the message leaves the alert open, and the click that opened it never finishes. A callback that runs later is easy to forget about, so put the handler right above the action that triggers it.
import { test, expect } from '@playwright/test';
test('a callback handles the browser alert', async ({ page }) => {
const messages = [];
page.on('dialog', async (dialog) => {
messages.push(dialog.message());
await dialog.accept();
});
await page.goto('/orders.html?mock=static&seed=42&autologin=1');
await page.getByTestId('archive-delivered').click();
expect(messages).toEqual(['Archiving is disabled in the practice environment.']);
});1 passed (1.5s)
page.on('dialog', (dialog) => console.log(dialog.message())) and then clicks a button that opens an alert. What happens?Related questions
AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.
163 lessons · 226 drills · start free