Automated testing is a crucial aspect of web development, ensuring that applications behave as expected under various conditions. When working with public APIs, like a weather API, it’s important to verify the accuracy of the data and the API’s responsiveness. Playwright, with its powerful testing capabilities, paired with TypeScript, provides an efficient way to automate these tests.
In this article, we'll explore how to write a simple Playwright test in TypeScript for a public weather API, while emphasizing the importance of Playwright in development.
Why Use Playwright for API Testing?
Playwright is generally known for its powerful browser automation features, but it's also highly effective for testing APIs. Here’s why it’s important:
- End-to-end API Testing: Playwright allows you to test entire workflows, ensuring that the application correctly fetches, processes, and displays data from APIs like a weather service.
- Real-world Scenarios: Simulating network conditions (e.g., slow connections or offline mode) and validating how your application handles such situations helps ensure robust API integration.
- Cross-browser Simulation: Playwright tests how the API response is handled across different browsers (Chromium, Firefox, WebKit), ensuring consistent behaviour regardless of the environment.
- TypeScript for Type Safety: Using TypeScript ensures that your tests are type-safe, making them easier to maintain, debug, and extend.
Setting Up Playwright with TypeScript
Before we start writing the test, let’s set up Playwright with TypeScript in a Node.js project.
Step 1: Initialize the Project
Create a new folder for your project and initialize it with npm
.
mkdir playwright-api-demo
cd playwright-api-demo
npm init -y
Step 2: Install Dependencies
Next, install Playwright and the required TypeScript packages.
npm install playwright
npm install -D typescript ts-node
Step 3: Initialize Playwright
Run the following command to install the necessary browsers and initialize Playwright.
npx playwright install
Step 4: Configure TypeScript
Create a tsconfig.json
file to configure TypeScript settings.
npx tsc --init
Make sure your tsconfig.json
looks something like this:
{
"compilerOptions": {
"target": "ESNext",
"module": "CommonJS",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
}
}
Writing the Playwright Test for a Weather API
Step 1: Create a Test File
Create a folder called tests/
and add a test file for the API.
mkdir tests
touch tests/weatherApi.spec.ts
Step 2: Write the Test
Here, we’ll write a Playwright test in TypeScript to validate the response from a weather API. We'll use a public weather API (such as OpenWeatherMap or any free weather API).
Here’s the test code in weatherApi.spec.ts
:
import { test, expect } from '@playwright/test';
const API_URL = 'https://api.openweathermap.org/data/2.5/weather';
const CITY = 'London';
const API_KEY = 'your_api_key'; // Replace with your actual API key
test('Weather API should return the correct data for a city', async ({ request }) => {
// Send a GET request to the weather API
const response = await request.get(`${API_URL}?q=${CITY}&appid=${API_KEY}&units=metric`);
// Check if the API request was successful
expect(response.status()).toBe(200);
// Parse the JSON response
const weatherData = await response.json();
// Validate that the response contains expected city name and main temperature data
expect(weatherData.name).toBe(CITY);
expect(weatherData.main).toHaveProperty('temp');
expect(weatherData.main).toHaveProperty('humidity');
expect(weatherData.weather.length).toBeGreaterThan(0);
});
Step 3: Understanding the Code
Test Structure: We define a test using Playwright’s
test()
function, providing a description and an async function that holds the test logic.API Request: We use Playwright’s
request.get()
to send a GET request to the weather API. The URL includes the city name (London
), the API key (your_api_key
), and query parameters to get the weather data in metric units.-
Assertions:
- We check that the API returns a
200
status code, meaning the request was successful. - We parse the JSON response using
response.json()
, then useexpect()
to validate that the returned data includes the correct city name and weather details like temperature and humidity.
- We check that the API returns a
Step 4: Run the Test
To run the Playwright test, use the following command:
npx playwright test
Playwright will run the test, make the API request, and validate the response.
Why Playwright for API Testing?
Playwright’s ability to handle API requests directly within the same test run, combined with its strong integration with browser automation, makes it a perfect tool for end-to-end testing. Here’s why it’s especially useful in development:
Full Workflow Testing: In a real-world application, API calls are rarely made in isolation. You’ll often want to test the integration of the API with your front-end. Playwright can combine browser automation (e.g., checking that the UI properly displays weather data) and API testing in a single workflow.
Simulating User Scenarios: You can simulate real user behavior, such as fetching weather data based on user input, testing different API endpoints (e.g., by city or GPS location), and checking how the application handles network issues or slow responses.
Cross-browser Compatibility: Playwright ensures that the API responses are handled consistently across multiple browsers, which is essential for delivering a consistent user experience.
CI/CD Integration: Playwright integrates easily with CI/CD pipelines, allowing you to continuously test your API integration. This ensures that your application works reliably, even as you add new features or updates to the API.
Handling Complex Scenarios: Playwright allows you to mock API responses, simulate slow or failed API requests, and test edge cases like network throttling, ensuring your app can handle real-world scenarios.
Conclusion
Playwright, combined with TypeScript, offers an efficient and scalable approach to testing public APIs like a weather service. By automating API tests, you ensure the accuracy of your application’s data, improve its reliability, and catch issues early in the development cycle. The ease of setup, flexibility, and integration with broader testing scenarios make Playwright an indispensable tool for developers aiming to create high-quality, stable applications.
By adopting Playwright for API testing, developers can confidently release applications that interact with external APIs, ensuring both functionality and consistency across different environments.
Top comments (0)