How to Test Failed Payment Messages in Playwright


Imagine a customer shopping online.

The customer adds a product to the cart, enters payment information, and clicks the Pay Now button.

After a few seconds, the application displays:

Payment Failed. Please try again.

But is that message correct?

Does the application display the right error for a declined card?

What happens when the card has expired?

What happens when the payment gateway is temporarily unavailable?

What happens when the internet connection is interrupted?

These are important questions for automation testers.

A payment application should not display the same confusing error for every problem.

Customers should receive clear messages that explain what happened and what they can safely do next.

For example:

  • A declined card should display an appropriate payment failure message.

  • An expired card should explain that the card has expired.

  • A network problem should explain that the payment status may need verification.

  • An invalid CVV should display an appropriate validation message.

This is why testing payment error messages is an important part of end-to-end automation testing.

How to Test Failed Payment Messages in Playwright is a common practical question for automation engineers working on e-commerce websites, banking applications, subscription platforms, and payment systems.

In this guide, you will learn how to validate payment failure messages using Playwright and TypeScript.

1. What Are Failed Payment Messages?

Failed payment messages are notifications displayed when a payment cannot be completed or requires additional action.

They help customers understand the payment result.

For example, suppose a customer attempts to pay ₹2,000 using a card.

The payment gateway declines the transaction.

The application may display:

"Your payment could not be completed. Please try another payment method."

This message informs the customer that the transaction was unsuccessful.

Payment failure messages may appear because of:

  1. Incorrect card information.

  2. Expired cards.

  3. Insufficient funds.

  4. Bank-declined transactions.

  5. Invalid CVV.

  6. Payment gateway errors.

  7. Network interruptions.

  8. Authentication failures.

  9. Session expiration.

  10. Payment processing timeouts.

Automation testers must verify that the application handles each situation correctly.

2. Why Should You Test Payment Error Messages?

Error messages are not just small notifications.

They directly affect customer confidence and the payment experience.

Consider these examples.

Scenario 1: Incorrect Error Message

A customer enters an expired card.

The application displays:

"Something went wrong."

This message does not explain the actual problem.

A better message would be:

"Your card has expired. Please use another payment method."

Scenario 2: Incorrect Success Message

The payment gateway rejects the transaction.

However, the application displays:

"Payment Successful."

This is a serious functional problem.

Scenario 3: Unclear Retry Instructions

The payment fails because of a temporary connection issue.

The application displays:

"Payment Failed."

But it does not explain whether the customer should retry or check the transaction status.

This can lead to accidental duplicate payments.

Scenario 4: Sensitive Information Exposure

The application displays too much technical information in an error message.

For example, it exposes internal server details or sensitive payment information.

A customer-facing error should provide useful guidance without revealing confidential technical information.

Therefore, payment error message testing must check correctness, clarity, security, and user experience.

3. Types of Payment Error Messages You Should Test

Before writing automation scripts, understand the different payment failure scenarios.

Scenario

Example Expected Message

Declined card

Your card was declined.

Expired card

Your card has expired.

Invalid CVV

Please check your security code.

Insufficient funds

Your payment could not be completed.

Invalid card number

Please enter valid card details.

Gateway unavailable

Payment service is temporarily unavailable.

Network interruption

We could not confirm your payment status.

Session expired

Your session has expired. Please start again.

Authentication failure

Payment authentication could not be completed.

Cancelled payment

You cancelled the payment.

These are illustrative messages.

Actual messages should follow the application's product requirements and payment provider's response mapping.

4. How to Test Failed Payment Messages Using Playwright

Playwright provides several ways to validate error messages.

The most common approach is to:

  1. Open the checkout page.

  2. Trigger a controlled payment failure.

  3. Wait for the application to process the response.

  4. Locate the error message.

  5. Verify the displayed text.

  6. Verify the payment status.

  7. Verify that the application does not incorrectly confirm the order.

Let's understand each step with practical examples.

5. How to Test an Invalid Payment Card Message

Imagine a shopping website where customers enter card details.

When the customer submits invalid card information, the application should display an appropriate validation message.

Playwright Example

import { test, expect } from '@playwright/test';


test('should display invalid card message', async ({ page }) => {


  await page.goto('/checkout');


  await page.getByLabel('Card Number')

    .fill('INVALID_TEST_CARD');


  await page.getByRole('button', {

    name: 'Pay Now'

  }).click();


  await expect(

    page.getByRole('alert')

  ).toContainText('Please enter valid card details');


});

Explanation

First, Playwright opens the checkout page.

await page.goto('/checkout');

Next, it enters invalid test data.

await page.getByLabel('Card Number')

  .fill('INVALID_TEST_CARD');

Then it clicks the payment button.

await page.getByRole('button', {

  name: 'Pay Now'

}).click();

Finally, it checks whether the application displays the expected error message.

await expect(

  page.getByRole('alert')

).toContainText('Please enter valid card details');

The test passes only when the expected text appears within the alert.

Important: This example assumes client-side validation. Some applications use hosted payment fields or validate card information through a gateway. Adapt the test to the actual payment architecture.

6. How to Test a Declined Payment Message

A declined payment occurs when the payment provider or issuing bank does not approve a transaction.

For example, the customer submits a payment, but the gateway returns a declined status.

The application should display the correct message.

Example: Simulate a Declined Payment API Response

import { test, expect } from '@playwright/test';


test('should display declined payment message', async ({ page }) => {


  await page.route('**/api/payments', async route => {


    await route.fulfill({

      status: 402,

      contentType: 'application/json',

      body: JSON.stringify({

        status: 'declined',

        message: 'Your card was declined'

      })

    });


  });


  await page.goto('/checkout');


  await page.getByRole('button', {

    name: 'Pay Now'

  }).click();


  await expect(

    page.getByRole('alert')

  ).toHaveText('Your card was declined');


});

What Happens Here?

The route() method intercepts a matching API request.

The fulfill() method sends a controlled response to the application.

The application receives a declined payment result.

Playwright then verifies whether the correct message appears.

This approach is useful when you want to test how the frontend handles different backend responses without making an actual payment.

However, it does not test whether the real payment gateway correctly declines a card.

For that, use the provider's official sandbox.

7. How to Test an Insufficient Funds Error

Insufficient funds means the account does not have enough available money to complete a transaction.

For example:

Available balance: ₹500.

Payment amount: ₹2,000.

The transaction cannot be completed.

The application should display an appropriate message.

Example

import { test, expect } from '@playwright/test';


test('should handle insufficient funds response', async ({ page }) => {


  await page.route('**/api/payments', async route => {


    await route.fulfill({

      status: 402,

      contentType: 'application/json',

      body: JSON.stringify({

        status: 'failed',

        code: 'INSUFFICIENT_FUNDS',

        message: 'Payment could not be completed'

      })

    });


  });


  await page.goto('/checkout');


  await page.getByRole('button', {

    name: 'Pay Now'

  }).click();


  await expect(

    page.getByRole('alert')

  ).toContainText('Payment could not be completed');


});

The application may show a more specific message depending on the payment provider and its error-handling rules.

The important thing is to verify the correct business response.

8. How to Test Payment Gateway Timeout Messages

A payment gateway timeout happens when the application does not receive a response within the expected time.

Imagine the customer clicks Pay Now.

The application sends a payment request.

But the gateway does not respond quickly enough.

The application must handle this situation carefully.

A timeout does not automatically mean that the transaction failed.

The gateway may have processed the payment even though the application did not receive confirmation.

Example: Simulate a Timeout Response

import { test, expect } from '@playwright/test';


test('should display payment verification message', async ({ page }) => {


  await page.route('**/api/payments', async route => {


    await route.fulfill({

      status: 504,

      contentType: 'application/json',

      body: JSON.stringify({

        status: 'unknown',

        message: 'Payment status could not be confirmed'

      })

    });


  });


  await page.goto('/checkout');


  await page.getByRole('button', {

    name: 'Pay Now'

  }).click();


  await expect(

    page.getByRole('alert')

  ).toContainText('Payment status could not be confirmed');


});

What Should You Verify?

  • The application displays an appropriate message.

  • The customer is not incorrectly told that payment succeeded.

  • The application does not immediately create another charge.

  • The transaction can be checked through an appropriate status-verification process.

  • The customer receives clear instructions.

This is particularly important for applications that process financial transactions.

9. How to Verify That a Failed Payment Does Not Confirm an Order

This is one of the most important negative testing scenarios.

Suppose a customer attempts to purchase a product.

The payment fails.

However, the application accidentally creates a confirmed order.

This is incorrect business behavior.

The test should verify that the order is not marked as paid.

Example

import { test, expect } from '@playwright/test';


test('should not confirm order after failed payment', async ({ page }) => {


  await page.route('**/api/payments', async route => {


    await route.fulfill({

      status: 402,

      contentType: 'application/json',

      body: JSON.stringify({

        status: 'failed'

      })

    });


  });


  await page.goto('/checkout');


  await page.getByRole('button', {

    name: 'Pay Now'

  }).click();


  await expect(

    page.getByTestId('payment-status')

  ).toHaveText('Failed');


  await expect(

    page.getByTestId('order-status')

  ).not.toHaveText('Confirmed');


});

Why Is This Important?

Payment status and order status are related, but they are not always the same thing.

An application may have statuses such as:

  • Payment Pending

  • Payment Failed

  • Payment Processing

  • Payment Completed

  • Order Pending

  • Order Confirmed

  • Order Cancelled

The expected relationship between these states must be defined by the application's business rules.

Your automation should verify those rules.

10. How to Test Multiple Payment Error Messages Using Playwright

A professional automation framework should avoid creating completely separate test logic for every similar scenario.

You can use data-driven testing to execute the same test with different payment responses.

This makes the test suite easier to maintain.

Example: Data-Driven Payment Error Testing

import { test, expect } from '@playwright/test';


const paymentErrors = [

  {

    code: 'CARD_DECLINED',

    message: 'Your card was declined'

  },

  {

    code: 'INVALID_CARD',

    message: 'Please enter valid card details'

  },

  {

    code: 'PAYMENT_UNAVAILABLE',

    message: 'Payment service is temporarily unavailable'

  }

];


for (const error of paymentErrors) {


  test(`should display ${error.code} message`, async ({ page }) => {


    await page.route('**/api/payments', async route => {


      await route.fulfill({

        status: 402,

        contentType: 'application/json',

        body: JSON.stringify({

          status: 'failed',

          code: error.code,

          message: error.message

        })

      });


    });


    await page.goto('/checkout');


    await page.getByRole('button', {

      name: 'Pay Now'

    }).click();


    await expect(

      page.getByRole('alert')

    ).toHaveText(error.message);


  });


}

Why Use Data-Driven Testing?

Imagine you have 20 payment error scenarios.

Without reusable test logic, you may end up writing almost the same test 20 times.

Data-driven testing allows you to maintain different input values and expected results in one place.

Benefits include:

  • Less duplicate code.

  • Easier test maintenance.

  • Better scenario coverage.

  • Consistent validation.

  • Easier addition of new test cases.

For more details, explore our Playwright data-driven testing concepts.

11. How to Test Error Messages for Correct Text and Visibility

Displaying an error message is not enough.

It must also be readable, visible, and accessible to the customer.

Playwright provides useful assertions for this purpose.

Check Whether the Error Message Is Visible

await expect(

  page.getByRole('alert')

).toBeVisible();

Check the Exact Error Message

await expect(

  page.getByRole('alert')

).toHaveText('Your card was declined');

Check Partial Error Text

await expect(

  page.getByRole('alert')

).toContainText('declined');

Check Whether the Error Message Disappears

await expect(

  page.getByRole('alert')

).toBeHidden();

This last example is useful when an application automatically removes an error message after the customer corrects the problem.

Use the assertion that matches the actual requirement.

12. Payment Error Message Testing: Common Mistakes

Mistake 1: Checking Only Whether an Error Exists

A weak test might check whether any error message appears.

But it may not verify whether the correct message appears.

Solution: Verify the expected error text.

Mistake 2: Ignoring Payment Status

An application may display an error message but still incorrectly update the payment status.

Solution: Verify both the message and transaction state.

Mistake 3: Using Unstable Locators

Using complex CSS selectors for every message can make tests difficult to maintain.

Solution: Prefer accessible locators such as getByRole() and getByLabel() when suitable.

Mistake 4: Testing Only One Failure Scenario

Different failures require different handling.

Solution: Build a payment error scenario matrix.

Mistake 5: Treating a Timeout as a Confirmed Failure

A timeout may leave the payment result uncertain.

Solution: Verify the transaction status before allowing another payment attempt.

Mistake 6: Ignoring Accessibility

An error message may be visually present but inaccessible to screen readers.

Solution: Use suitable semantic markup, accessible labels, and alert roles.

13. Payment Error Message Testing Best Practices

Follow these practices when building a reliable Playwright test suite.

  1. Test different payment failure codes.

  2. Verify exact or approved message text.

  3. Check error message visibility.

  4. Verify the correct payment status.

  5. Check that failed payments do not create paid orders.

  6. Test gateway timeout scenarios.

  7. Test network failure handling.

  8. Verify retry instructions.

  9. Check accessibility of error notifications.

  10. Avoid exposing sensitive information.

  11. Use sandbox payment scenarios.

  12. Capture screenshots and traces for failures.

  13. Keep test data reusable.

  14. Validate actual application business requirements.

14. Frequently Asked Questions

How do you test failed payment messages in Playwright?

Use Playwright to trigger a controlled payment failure, wait for the application response, and verify the displayed error message using assertions such as toHaveText(), toContainText(), and toBeVisible().

How do you validate payment error messages?

You can validate payment error messages by checking their text, visibility, accessibility, and relationship with the payment transaction status.

Can Playwright test declined card messages?

Yes. You can use a payment gateway sandbox or simulate a declined payment API response using Playwright network interception.

How do you test payment timeout errors?

Simulate a timeout or an appropriate uncertain payment response, then verify that the application displays the correct message and follows its transaction verification process.

How do you test multiple payment errors?

Use data-driven testing with different error codes and expected messages. This allows you to execute multiple payment failure scenarios using reusable automation logic.

Which Playwright assertion is best for error message testing?

Use toHaveText() when the complete message must match, toContainText() when only part of the message matters, and toBeVisible() when you need to verify that the message is displayed.

Why is negative testing important in payment applications?

Negative testing checks how an application behaves when something goes wrong. It helps identify incorrect transaction statuses, misleading messages, duplicate charges, and unsafe retry behavior.

Conclusion

Payment error message testing is an important part of building reliable automation frameworks.

A professional tester should not simply verify whether an error message appears.

The tester must understand why the payment failed, whether the application displays the correct message, whether the transaction status is accurate, and whether the customer can safely continue.

Playwright makes this process easier through browser automation, network interception, reusable assertions, and API testing.

By combining these techniques, automation engineers can create meaningful payment failure test cases that reflect real customer experiences.

Learn more about real-world Playwright automation, API testing, assertions, and framework development with PlaywrightMasters.


Comments

Popular posts from this blog

How to Run Only Smoke Tests in Playwright: Step-by-Step Guide

How to Test REST APIs Using Playwright

Playwright Multiple Tabs and Windows Explained: A Practical Guide