Stubbing Backends

One common source of problems with Selenium tests is that the backend may not be stable. This makes your test seem flaky and you can spend a lot of time hunting for problems in your tests that simply don't exist. Selenium 4 has a feature that allows you to snap out some or all of the HTTP requests that the browser makes. Let's try this out by replacing the logo of a well-known search engine with a Selenium checkmark.

What we're going to do is going to go to this well-known website, duckduckgo. OK, I'm going to replace the DuckDuckGo logo with the Selenium tick, so we're going to do. So in order to do that, we're going to do some network interception.

So I'm going to go to DukDuckGo. Right. And in order to do this, what we need is we need to have loaded the tick. So this is loading the tick from here. And we'll have that available to us. And what we want to do is we want to have a new try booked, good and we're going to have a network interceptor. Interceptor text driver, text route, we don't have the route yet, but we're just about to write that. So what is the route?

The route comes from the Selenium HTTP package, and the first thing we need to do is match against a incoming request. So when we see a request where URi contains the word Logo and ends with .svg. Why do we want this, because here, this logo here, it's located here. So we want to have a request for logo svg and what we're going to do, we're going to replace that logo.

To this supplier of HTTP and HTTP handler takes a request and returns a response near HTTP response, addHeader I'll set the content type correctly because that's always a good thing to do. Have content type just here, this does help the class that does all sorts of clever things. We just want the bytes to be loaded here which contains the tick. So that's a whole test. The key bit is here and we make sure that that is used by the driver with this line here. And there you go, we have replaced it with the logo. 

Comments are closed.

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}