Styrow.dev
Question 28 of 28

How do you architect a Playwright test to verify atomic transaction rollback across UI and API state?

Question

How do you architect a Playwright test to verify atomic transaction rollback across UI and API state?

Answer

The challenge is to design a resilient E2E test flow in Playwright that verifies a complex, multi-stage transaction (e.g., an order placement involving payment, inventory update, and notification services). The transaction is designed to be atomic, meaning if any step fails (e.g., inventory service throws an exception after payment was processed), the entire transaction must roll back, and the UI must reflect a consistent failure state.

A naive approach using simple await page.click() and await expect(page.locator('.error')).toBeVisible() is insufficient because the UI might briefly display a “processing” state while the backend is asynchronously rolling back.

Describe the architectural approach using Playwright features (e.g., interceptors, custom context management, API mocks) to achieve the following:

  1. Forced Failure Injection: How do you reliably force the intermediate API call (e.g., the inventory service call) to fail after the preceding successful call (e.g., payment service call) has executed, thereby triggering the rollback mechanism?
  2. Verification of Rollback: How do you assert, within the test, that the rollback succeeded? This requires verifying two things simultaneously: (a) The UI correctly displays the failure state, AND (b) The backend state (e.g., checking the inventory service endpoint directly or via a dedicated API assertion) confirms that the resources were released or never committed.
  3. Test Resilience: How do you structure the assertion logic to handle potential transient states during the rollback process, ensuring the test doesn’t fail prematurely but waits for the final, consistent state (either success or confirmed rollback)?

Provide a high-level pseudo-code structure demonstrating the combination of these techniques.