How to use RouteFulfillOptions method of Microsoft.Playwright.RouteFulfillOptions class

Best Playwright-dotnet code snippet using Microsoft.Playwright.RouteFulfillOptions.RouteFulfillOptions

Run Playwright-dotnet automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Program.cs

Source: Program.cs Github

copy
1using Microsoft.Playwright;
2using System.Threading.Tasks;
3using System.Collections.Generic;  
4using System;  
5using System.IO;  
6using System.Text.Json;
7
8class Program
9{
10    public static async Task Main()
11    {
12        UsersContext context = new UsersContext();
13        using var playwright = await Playwright.CreateAsync();
14        await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions{
15            Headless = false, 
16            SlowMo = 2000
17        });
18        var page = await browser.NewPageAsync();
19        
20        var url  =  "http://localhost:4200/";
21        
22        string usersUrl  =  "https://jsonplaceholder.typicode.com/**";
23
24        await page.RouteAsync(usersUrl,async route => {
25            
26            if(route.Request.Method.ToUpperInvariant() == "GET"){
27                await route.FulfillAsync(new RouteFulfillOptions { 
28                    Status = 200
29                    , ContentType = "application/json"
30                    , Headers = new List<KeyValuePair<string, string>>{ 
31                            new KeyValuePair<string, string>("Access-Control-Allow-Credentials", "true" ),  
32                            new KeyValuePair<string, string>("Access-Control-Allow-Origin", "*" ),  
33                        }
34                    , Body = context.Data });
35            }
36            else if(route.Request.Method.ToUpperInvariant() == "PUT"){
37             
38                context.UpdateUser(route.Request.PostData);
39                
40                await route.FulfillAsync(new RouteFulfillOptions { 
41                    Status = 200
42                    , ContentType = "application/json"
43                    , Headers = new List<KeyValuePair<string, string>>{ 
44                            new KeyValuePair<string, string>("Access-Control-Allow-Credentials", "true" ),  
45                            new KeyValuePair<string, string>("Access-Control-Allow-Origin", "*" ),  
46                        }
47                    , Body = route.Request.PostData });
48            }
49            else{
50                await route.ContinueAsync();
51            }
52         });
53
54        await page.GotoAsync(url);
55        
56        await page.Locator("text=Leanne Graham").ClickAsync();;
57
58        var number = new Random().Next(0, 1000000).ToString("D6");
59
60        await page.FillAsync("input[aria-label=name]", $"Leanne Graham {number}");
61        await page.FillAsync("input[aria-label=username]", $"Bret {number}");
62        await page.FillAsync("input[aria-label=email]", $"Sincere{number}@april.biz");
63
64        await page.Locator("button[aria-label=btn-save]").ClickAsync();;
65
66        //This line is just to put wait on the browser
67        await page.Locator("button[aria-label=btn-none]").ClickAsync();;
68
69        await page.ScreenshotAsync(new PageScreenshotOptions { Path = "screenshot.png" });
70
71        await browser.CloseAsync();
72    }
73}
74
75
Full Screen

UnitTest1.cs

Source: UnitTest1.cs Github

copy
1using System;
2using System.Collections.Generic;
3using System.Threading.Tasks;
4using Microsoft.Playwright;
5using NUnit.Framework;
6using Newtonsoft.Json;
7
8namespace PlaywrightTests;
9
10public class Tests
11{
12    public IBrowser _Browser { get; set;}
13    public IPlaywright _Playwright { get; set;}
14    public IBrowserContext _Context { get; set; }
15
16    public IPage _Page { get; set; }
17
18    [OneTimeSetUp]
19    public async Task SetupAsync()
20    {
21        var playwright = await Playwright.CreateAsync();
22        _Playwright = playwright;
23
24        var browserLaunchOptions = new BrowserTypeLaunchOptions { 
25                Headless = false
26        };
27        var browser = await playwright.Chromium.LaunchAsync(browserLaunchOptions);
28        _Browser = browser;
29
30        _Context = await _Browser.NewContextAsync();
31
32        _Page = await _Context.NewPageAsync();
33    }
34
35    [TearDown]
36    public async Task TearDownAsync(){
37        Console.WriteLine(await _Page.TitleAsync());
38        await _Page.PauseAsync();
39    }
40
41    [OneTimeTearDown]
42    public async Task OneTimeTearDownAsync(){
43        await _Context.CloseAsync();
44        await _Browser.CloseAsync();
45        _Playwright.Dispose();
46    }
47
48    [Test]
49    public async Task InterceptContent()
50    {
51        await _Page.RouteAsync("**/*", async route =>{
52            if(route.Request.ResourceType == "stylesheet" ){
53                await route.AbortAsync();
54            }
55            else {
56                await route.ContinueAsync();
57            }
58        });
59        await _Page.GotoAsync("https://danube-webshop.herokuapp.com/");
60    }
61    [Test]
62    public async Task InterceptResponses()
63    { 
64        Object[] mockResponseObject = {new {
65            id =  1,
66            title = "How to Mock a Response",
67            author = "A. Friend",
68            genre = "business",
69            price = "0.00",
70            rating = "★★★★★",
71            stock = 65535
72        }};
73        var list = new List<object>(){mockResponseObject};
74        await _Page.RouteAsync("https://danube-webshop.herokuapp.com/api/books", async route =>{
75            await route.FulfillAsync(new RouteFulfillOptions {
76                ContentType = "application/json",
77                Body = JsonConvert.SerializeObject(mockResponseObject)
78            });
79        });
80        await _Page.GotoAsync("https://danube-webshop.herokuapp.com/");
81    }
82}
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used method in RouteFulfillOptions

Trigger RouteFulfillOptions code on LambdaTest Cloud Grid

Execute automation tests with RouteFulfillOptions on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)