Skip to main content

Mock server

 Using a mock server in end-to-end (E2E) testing is indeed common, and it can be used for more than just reading values. Mock servers simulate the behavior of real servers and can handle various HTTP methods, including POST, PUT, DELETE, and PATCH, in addition to GET. This means you can use a mock server to simulate interactions that involve writing data, such as filling out and submitting forms.

Automating Form Interactions with Mock Servers

  1. Simulating Form Submissions: Mock servers can be set up to handle form submissions. When you submit a form in your E2E test, the mock server can capture the request and respond with a predefined response.

  2. Validating Data: You can use the mock server to validate the data sent by your application. The mock server can check if the request body matches the expected format and values.

  3. Response Handling: After submitting a form, your application typically processes the server's response. The mock server can provide specific responses to test how your application handles different scenarios (e.g., successful submission, validation errors, server errors).

Example with Playwright and Mock Server

Let's say you have a form with fields for username and email, and you want to automate the form submission using Playwright and a mock server.

Mock Server Setup

Using a simple Node.js mock server with Express:

javascript
// mockServer.js const express = require('express'); const app = express(); app.use(express.json()); app.post('/submit-form', (req, res) => { const { username, email } = req.body; if (username && email) { res.status(200).json({ message: 'Form submitted successfully' }); } else { res.status(400).json({ message: 'Invalid form data' }); } }); app.listen(3000, () => { console.log('Mock server running on http://localhost:3000'); });

Playwright E2E Test

Using Playwright to automate the form submission:

typescript
// form.spec.ts import { test, expect } from '@playwright/test'; test('should submit form successfully', async ({ page }) => { await page.goto('http://localhost:3000/form'); // Your app's form URL await page.fill('#username', 'testuser'); await page.fill('#email', 'testuser@example.com'); // Intercept the form submission request and mock the response await page.route('**/submit-form', route => { route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ message: 'Form submitted successfully' }), }); }); await page.click('#submit-button'); // Check for success message const successMessage = await page.locator('#success-message'); await expect(successMessage).toHaveText('Form submitted successfully'); });

Benefits of Using Mock Servers in E2E Tests

  1. Control Over Responses: You can control the responses from the server, making it easier to test different scenarios without depending on an actual backend.
  2. Isolation: Your tests can run in isolation without affecting or depending on the actual server, which is useful for CI/CD pipelines.
  3. Speed: Mock servers are generally faster than real servers, which can speed up your test suite.
  4. Consistency: The mock server ensures that the responses are consistent, which helps in creating reliable tests.

Summary

Mock servers are versatile tools in E2E testing. They can be used not only for reading data but also for simulating form submissions and other write operations. By intercepting requests and providing predefined responses, mock servers allow you to create controlled and predictable test environments, ensuring your application's interactions are thoroughly tested.

Comments

Popular posts from this blog

Get OTP from email

/** * Retrieves an OTP from Gmail in a headless tab. * @param {Object} options - The options for the function. * @param {string} options.email - The Gmail email address. * @param {string} options.password - The Gmail password. * @returns {Promise<string | null>} The OTP retrieved from the email. */ export async function getOtpFromGmail ({ email , password , } : { email : string ; password : string ; }) : Promise < string | null > { const { chromium } = require ( "playwright" ); // Launch a headless browser context for Gmail login const browser = await chromium . launch ({ headless : true }); const context = await browser . newContext (); const page = await context . newPage (); await page . goto ( "https://mail.google.com" ); const emailInput = await page . waitForSelector ( "#identifierId" ); await emailInput . fill ( email ); const emailNextButton = await page . wa...

Playwright Solution

 There is a web site need to run with browser. and which has zero downtime and alert and notifications pop up too. Third party applications are involved in and need to fix bugs too.What is the solution and how to create a framework for this scenario : need to use playwright as well 1. Understand the Requirements and Challenges: Zero Downtime: Ensure tests do not interrupt the service. Alerts and Notifications: Handle unexpected pop-ups gracefully. Third-Party Integrations: Test interactions with third-party services. Bug Fixing: Implement a process to identify and log bugs efficiently. 2. Set Up the Playwright Framework: Installation: Ensure Playwright is installed and configured. bash Copy code npm install playwright 3. Structure the Test Framework: Test Suites: Organize tests into suites (e.g., smoke tests, regression tests, integration tests). Page Object Model (POM): Use POM to manage page elements and actions. Configuration: Set up configurations for different envir...

Challenges

 One of the challenging situations I faced was identifying the correct locators for elements in our Angular application. Despite using developer tools like Chrome DevTools, it was often difficult to pinpoint the exact locators due to the complexity of the application and the dynamic nature of Angular's rendering. To overcome this, I frequently had to review the application's code in Bitbucket to understand the structure and find reliable locators. This approach allowed me to write more robust and reliable tests. Additionally, I communicated with developers to gain insights and confirm my findings, which helped streamline the process." As our application grew, the number of test scripts also increased, making the scripts larger and more chaotic. This was especially true for our end-to-end tests using Playwright and TypeScript. The test scripts became hard to manage and maintain because they contained both the test logic and the test data, leading to a lot of redundancy and ...