Testing web applications can be challenging, but Playwright offers powerful tools to make it easier. Among these are browser contexts and sessions, which are essential for creating reliable and isolated test environments. This guide will walk you through how to use Playwright browser contexts and sessions with TypeScript. We’ll provide detailed explanations and practical examples to help you ensure your site works seamlessly under various conditions.
Understanding Browser Contexts and Its Benefits
What is a Browser Context?
A Playwright browser context is like a separate profile. It’s a clean slate within a single browser instance. Each context isolates itself from the others. It has its own cookies, local storage, and cache. This isolation is crucial for testing. It lets you simulate users or states without interference.
For instance, to test how two users interact with your app at once, use separate contexts for each user. This ensures that their sessions do not overlap or affect one another.
Key Features of Browser Contexts:
- Isolation:
- Session Management: Each context maintains its own session data. This means that logging into an app in one context will not affect the login state in another.
- Data Separation: Cookies, local storage, and session data are unique to each context. This prevents data leakage between contexts.
- Multiple Contexts:
- Parallel Testing: Multiple contexts allow you to perform parallel tests or operations. For instance, you can test different user roles at once in a single browser.
- Resource Efficiency: Use multiple tabs in one browser, not several browsers.
- User Simulation:
- Different User Scenarios: You can simulate different users with unique sessions and states. This is useful for testing applications under various user conditions without interference.
- State Management: Use different contexts to control app states, such as when a user logs in or out, to manage the state. Also, test features that might be on or off.
Benefits of Using Browser Contexts:
- Improved Testing Efficiency:
- Faster Execution: Running tests in different contexts at the same time speeds them up.
- Consistency: Running tests in separate contexts avoids issues from old data. This makes the results more reliable.
- Enhanced Security and Privacy:
- Data Isolation: Sensitive data stays within its context. This reduces the risk of accidental sharing or leaks.
- Avoiding Detection: In web scraping, using multiple contexts can help avoid detection. It can flag repetitive requests in automated interactions.
- Flexible Debugging and Development:
- Simulating Real-World Scenarios: Developers can create scenarios by tweaking specific data. This enables precise issue detection and swift resolution.
- Debugging: Isolation helps to debug issues that may vary by user state or session.
How to Create and Use Browser Contexts?
Here’s a more detailed look at how you might create and use browser contexts in Playwright. Playwright enables you to streamline browser context management. Here’s an example of creating and using contexts in Playwright:
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
// Create a new browser context
const context1 = await browser.newContext();
// Optionally, configure the context
await context1.addCookies([{ name: 'cookie_name', value: 'cookie_value', url: 'https://example.com' }]);
// Open a new page in the context
const page1 = await context1.newPage();
await page1.goto('https://example.com');
// Create another browser context
const context2 = await browser.newContext();
const page2 = await context2.newPage();
await page2.goto('https://example.org');
await browser.close();
})(); Isolating Tests Using Different Contexts and Sessions
Let’s explore a practical example. It will use browser contexts in TypeScript to test multiple user logins at once. This teaches the skills to craft and govern multiple contexts.
Setting Up Your Project:
- First, ensure you have Playwright and TypeScript installed in your project. If not, use these commands to initialize your project and install the packages:
npm install playwright typescript ts-node
Example: Testing Multiple User Logins
We will test how two users log into the same app. We must ensure that we isolate their sessions.
- Create a TypeScript file named login.test.ts and include the following code:
import { chromium, Browser, Page } from 'playwright';
(async () => {
// Launch a new Chromium browser instance
const browser: Browser = await chromium.launch();
// Create two different browser contexts
const context1 = await browser.newContext();
const context2 = await browser.newContext();
// Create new pages in each context
const page1: Page = await context1.newPage();
const page2: Page = await context2.newPage();
// Test login for the first user
await page1.goto('https://example.com/login');
await page1.fill('input[name="username"]', 'user1');
await page1.fill('input[name="password"]', 'password1');
await page1.click('button[type="submit"]');
// Check if login was successful for user1
const welcomeMessage1 = await page1.textContent('.welcome-message');
console.log('User1: ', welcomeMessage1);
// Test login for the second user
await page2.goto('https://example.com/login');
await page2.fill('input[name="username"]', 'user2');
await page2.fill('input[name="password"]', 'password2');
await page2.click('button[type="submit"]');
// Check if login was successful for user2
const welcomeMessage2 = await page2.textContent('.welcome-message');
console.log('User2: ', welcomeMessage2);
// Close the browser
await browser.close();
})(); Explanation:
- Launching the Browser: Use the chromium.launch() method. It starts a new instance of the Chromium browser. This instance will host many contexts.
- Creating Contexts: To create two separate browser contexts, we call browser.newContext() twice. Each context isolates itself from the others. It lets you simulate different user environments.
- Creating Pages: Within each context, you create a new page by using context.newPage(). This is where the test interactions with the application will occur.
- Running Tests: For each context, the script navigates to the login page. It then logs in with different credentials. Finally, it checks the welcome message to see if the login was successful.
- Closing the Browser: We call browser.close() after all tests to close the browser and clean up.
Managing Cookies, Storage, and Permissions:
Playwright provides tools to manage cookies and local storage. It also manages permissions on a per-context basis. This is vital for testing scenarios with session data and user permissions.
Managing Cookies:
Cookies are often used to maintain session information or user preferences. Playwright allows you to add, retrieve, and clear cookies within a specific context.
// Add a cookie to context1
await context1.addCookies([{
name: 'session_id',
value: 'abcd1234',
domain: 'example.com',
path: '/'
}]);
// Retrieve cookies from context1
const cookies = await context1.cookies();
console.log('Cookies in context1: ', cookies);
Managing Local Storage:
Users keep data on their devices to maintain session continuity. You can manage local storage within a context. This tests how your app handles different user settings.
// Set an item in local storage for page1
await page1.evaluate(() => {
localStorage.setItem('user_theme', 'dark');
});
// Clear local storage for page1
await page1.evaluate(() => {
localStorage.clear();
});
Managing Permissions:
It’s important to manage permissions, like geolocation access. Testing features that rely on them need them. You can grant or deny permissions within a context.
// Grant geolocation permissions for context1
await context1.grantPermissions(['geolocation'], {
origin: 'https://example.com'
});
Advanced Use Cases
Testing Different User Roles:
Sometimes, you need to test different user roles within the same application. You can simulate different roles by creating many contexts. This will ensure that role-specific functions work as expected.
// Create a context for an admin user
const adminContext = await browser.newContext();
const adminPage = await adminContext.newPage();
// Create a context for a regular user
const userContext = await browser.newContext();
const userPage = await userContext.newPage();
Simulating Different Devices:
Playwright also lets you simulate device settings, like screen size and user agent. Change the context settings to do this.
// Create a mobile context with specific viewport size
const mobileContext = await browser.newContext({
viewport: { width: 375, height: 667 },
userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/537.36 (KHTML, like Gecko) Version/10.0 Mobile/14E5239e Safari/537.36'
});
Conclusion
Playwright lets you create separate browser environments, called contexts, to run your tests. It helps keep tests separate and prevents conflicts. It handles user sessions with simplicity. Using TypeScript with Playwright helps you write clear and easy-to-maintain tests. You can test different user roles, handle cookies, and check various permissions. Playwright tests your app in various scenarios. It ensures it works well for users. It can manage isolated testing environments. So, it’s great for automated testing.
















