How to use RequestRespondTests method of PuppeteerSharp.Tests.RequestInterceptionTests.RequestRespondTests class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Tests.RequestInterceptionTests.RequestRespondTests.RequestRespondTests

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

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

RequestRespondTests.cs

Source: RequestRespondTests.cs Github

copy
1using System.Collections.Generic;
2using System.IO;
3using System.Net;
4using System.Threading.Tasks;
5using PuppeteerSharp.Tests.Attributes;
6using PuppeteerSharp.Xunit;
7using Xunit;
8using Xunit.Abstractions;
9
10namespace PuppeteerSharp.Tests.RequestInterceptionTests
11{
12    [Collection(TestConstants.TestFixtureCollectionName)]
13    public class RequestRespondTests : PuppeteerPageBaseTest
14    {
15        public RequestRespondTests(ITestOutputHelper output) : base(output)
16        {
17        }
18
19        [PuppeteerTest("requestinterception.spec.ts", "Request.respond", "should work")]
20        [SkipBrowserFact(skipFirefox: true)]
21        public async Task ShouldWork()
22        {
23            await Page.SetRequestInterceptionAsync(true);
24            Page.Request += async (_, e) =>
25            {
26                await e.Request.RespondAsync(new ResponseData
27                {
28                    Status = HttpStatusCode.Created,
29                    Headers = new Dictionary<string, object>
30                    {
31                        ["foo"] = "bar"
32                    },
33                    Body = "Yo, page!"
34                });
35            };
36
37            var response = await Page.GoToAsync(TestConstants.EmptyPage);
38            Assert.Equal(HttpStatusCode.Created, response.Status);
39            Assert.Equal("bar", response.Headers["foo"]);
40            Assert.Equal("Yo, page!", await Page.EvaluateExpressionAsync<string>("document.body.textContent"));
41        }
42
43        /// <summary>
44        /// In puppeteer this method is called ShouldWorkWithStatusCode422.
45        /// I found that status 422 is not available in all .NET runtimes (see https://github.com/dotnet/core/blob/4c4642d548074b3fbfd425541a968aadd75fea99/release-notes/2.1/Preview/api-diff/preview2/2.1-preview2_System.Net.md)
46        /// As the goal here is testing HTTP codes that are not in Chromium (see https://cs.chromium.org/chromium/src/net/http/http_status_code_list.h?sq=package:chromium&g=0) we will use code 426: Upgrade Required
47        /// </summary>
48        [PuppeteerTest("requestinterception.spec.ts", "Request.respond", "should work with status code 422")]
49        [SkipBrowserFact(skipFirefox: true)]
50        public async Task ShouldWorkReturnStatusPhrases()
51        {
52            await Page.SetRequestInterceptionAsync(true);
53            Page.Request += async (_, e) =>
54            {
55                await e.    Request.RespondAsync(new ResponseData
56                {
57                    Status = HttpStatusCode.UpgradeRequired,
58                    Body = "Yo, page!"
59                });
60            };
61
62            var response = await Page.GoToAsync(TestConstants.EmptyPage);
63            Assert.Equal(HttpStatusCode.UpgradeRequired, response.Status);
64            Assert.Equal("Upgrade Required", response.StatusText);
65            Assert.Equal("Yo, page!", await Page.EvaluateExpressionAsync<string>("document.body.textContent"));
66        }
67
68        [PuppeteerTest("requestinterception.spec.ts", "Request.respond", "should redirect")]
69        [SkipBrowserFact(skipFirefox: true)]
70        public async Task ShouldRedirect()
71        {
72            await Page.SetRequestInterceptionAsync(true);
73
74            Page.Request += async (_, e) =>
75            {
76                if (!e.Request.Url.Contains("rrredirect"))
77                {
78                    await e.Request.ContinueAsync();
79                    return;
80                }
81
82                await e.Request.RespondAsync(new ResponseData
83                {
84                    Status = HttpStatusCode.Redirect,
85                    Headers = new Dictionary<string, object>
86                    {
87                        ["location"] = TestConstants.EmptyPage
88                    }
89                });
90            };
91
92            var response = await Page.GoToAsync(TestConstants.ServerUrl + "/rrredirect");
93
94            Assert.Single(response.Request.RedirectChain);
95            Assert.Equal(TestConstants.ServerUrl + "/rrredirect", response.Request.RedirectChain[0].Url);
96            Assert.Equal(TestConstants.EmptyPage, response.Url);
97        }
98
99        [PuppeteerTest("requestinterception.spec.ts", "Request.respond", "should allow mocking binary responses")]
100        [SkipBrowserFact(skipFirefox: true)]
101        public async Task ShouldAllowMockingBinaryResponses()
102        {
103            await Page.SetRequestInterceptionAsync(true);
104            Page.Request += async (_, e) =>
105            {
106                var imageData = File.ReadAllBytes("./Assets/pptr.png");
107                await e.Request.RespondAsync(new ResponseData
108                {
109                    ContentType = "image/png",
110                    BodyData = imageData
111                });
112            };
113
114            await Page.EvaluateFunctionAsync(@"PREFIX =>
115            {
116                const img = document.createElement('img');
117                img.src = PREFIX + '/does-not-exist.png';
118                document.body.appendChild(img);
119                return new Promise(fulfill => img.onload = fulfill);
120            }", TestConstants.ServerUrl);
121            var img = await Page.QuerySelectorAsync("img");
122            Assert.True(ScreenshotHelper.PixelMatch("mock-binary-response.png", await img.ScreenshotDataAsync()));
123        }
124
125        [PuppeteerTest("requestinterception.spec.ts", "Request.respond", "should stringify intercepted request response headers")]
126        [SkipBrowserFact(skipFirefox: true)]
127        public async Task ShouldStringifyInterceptedRequestResponseHeaders()
128        {
129            await Page.SetRequestInterceptionAsync(true);
130            Page.Request += async (_, e) =>
131            {
132                await e.Request.RespondAsync(new ResponseData
133                {
134                    Status = HttpStatusCode.OK,
135                    Headers = new Dictionary<string, object>
136                    {
137                        ["foo"] = true
138                    },
139                    Body = "Yo, page!"
140                });
141            };
142
143            var response = await Page.GoToAsync(TestConstants.EmptyPage);
144            Assert.Equal(HttpStatusCode.OK, response.Status);
145            Assert.Equal("True", response.Headers["foo"]);
146            Assert.Equal("Yo, page!", await Page.EvaluateExpressionAsync<string>("document.body.textContent"));
147        }
148
149        [SkipBrowserFact(skipFirefox: true)]
150        public async Task ShouldAllowMultipleInterceptedRequestResponseHeaders()
151        {
152            await Page.SetRequestInterceptionAsync(true);
153            Page.Request += async (_, e) =>
154            {
155                await e.Request.RespondAsync(new ResponseData
156                {
157                    Status = HttpStatusCode.OK,
158                    Headers = new Dictionary<string, object>
159                    {
160                        ["foo"] = new bool[] { true, false },
161                        ["Set-Cookie"] = new string[] { "sessionId=abcdef", "specialId=123456" }
162                    },
163                    Body = "Yo, page!"
164                });
165            };
166
167            var response = await Page.GoToAsync(TestConstants.EmptyPage);
168            var cookies = await Page.GetCookiesAsync(TestConstants.EmptyPage);
169
170            Assert.Equal(HttpStatusCode.OK, response.Status);
171            Assert.Equal("True\nFalse", response.Headers["foo"]);
172            Assert.Equal("Yo, page!", await Page.EvaluateExpressionAsync<string>("document.body.textContent"));
173            Assert.Equal("specialId", cookies[0].Name);
174            Assert.Equal("123456", cookies[0].Value);
175            Assert.Equal("sessionId", cookies[1].Name);
176            Assert.Equal("abcdef", cookies[1].Value);
177        }
178    }
179}
180
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

Trigger RequestRespondTests code on LambdaTest Cloud Grid

Execute automation tests with RequestRespondTests 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)