What's the way to make sure that certain functions get called in Playwright? In Jest, I could spy on a listener by doing
const handleSubmit = jest.fn();
// ... Later
expect(handleSubmit).toHaveBeenCalled();
I could do something similar if I needed to check that certain functions within a handler were called too. Is there a way to do this in Playwright?
This thread is trying to answer question "Is there a way to create mock functions or check if certain functions or event handlers were called in Playwright, similar to how it's done in Jest?"
Related Ask AI answer for "How do I create mock functions and check if certain functions were called in Playwright?".
Sure, you can mock functions and check if they were called in Playwright. Let's dive in!
Playwright lets you intercept and modify network traffic, including HTTP requests. You can use the page.route()
method to create a mock function. This method intercepts calls to a specific URL pattern and lets you define custom logic for handling those requests.
Here's an example:
await page.route('https://ray.run/api/v1/fruits', async route => {
const response = await route.fetch();
const json = await response.json();
// Add 'playwright' fruit
json.push({ name: 'Playwright', id: 100 });
// Fulfill using modified JSON
await route.fulfill({ response, json });
});
In this example, we're mocking a call to an API endpoint /api/v1/fruits
. We fetch the original response, parse it as JSON, add a new fruit object, and then fulfill the request using the modified response data.
To check if certain functions were called, you can use assertions provided by testing frameworks like Jest or Playwright Test.
Here's an example:
test('checks if function was called on button click', async ({ page }) => {
// Mock the function
const mockFunction = jest.fn();
// Attach the mock function to a button click event
await page.evaluate(() => {
const button = document.querySelector('#myButton');
button.addEventListener('click', () => {
mockFunction();
});
});
// Click the button
await page.click('#myButton');
// Check if the mock function was called
expect(mockFunction).toHaveBeenCalled();
});
In this example, we create a mock function, attach it to a button's click event, click the button, and then check if our mock function was called.
That's it! With Playwright, you can create detailed and comprehensive tests for your applications. For more tips, check out Mastering Playwright Test Automation: Your Comprehensive Cheat Sheet.
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 [email protected].