Mocking API Response | Bondar Academy
Course: Playwright UI Testing with TypeScript
Module: Interacting with APIs
Instructor: Artem Bondar
Lesson Summary
In this lesson, we will learn how to mock API requests , which is useful for replacing actual server responses with our own. This technique can help in testing scenarios and dealing with unstable API endpoints, making tests more reliable. Key Concepts Mocking API Responses: Allows for faster loading times and stable tests by providing predefined responses. Playwright Framework: A tool used to intercept API calls and configure mocks before the browser makes requests. Steps to Mock API Requests Open the Networking Tab in the browser's developer tools to observe API calls. Use page.route to intercept the API endpoint you want to mock. Create a mock object with the desired response data. Use await route.fulfill to send the mock response, ensuring to JSON.stringify the object. Run the test to verify that the mock is functioning correctly. Refactoring the Mock To improve code organization: Create a test data folder and store the mock data in a text.json file. Import the JSON file in your test using the appropriate import syntax. Use wildcards in the URL to simplify the matching pattern for API calls. In summary, mocking API calls in Playwright involves setting up routes before the browser makes requests, creating mock data, and ensuring the application receives the desired responses during testing.