playwrightium icon indicating copy to clipboard operation
playwrightium copied to clipboard

Network interception and mocking

Open Krishna-D-Hegde opened this issue 1 year ago • 2 comments

Krishna-D-Hegde avatar Sep 08 '24 17:09 Krishna-D-Hegde

@Krishna-D-Hegde Thanks for this comment, I plan to add this functionality in next release

britka avatar Sep 15 '24 16:09 britka

Dear @Krishna-D-Hegde Actually you can always do that doing like this,

....
Webdriver driver = new PlaywrightiumDriver();
.....
Page page = ((PlaywrightiumDriver)driver).getPage()

page - the Playwright page object. So after that you may add e.g.

page.route("*/**/api/v1/fruits", route -> {
            List<Dictionary<String, Object>> data = new ArrayList<>();
            Hashtable<String, Object> dict = new Hashtable<>();
            dict.put("name", "Strawberry");
            dict.put("id", 21);
            data.add(dict);
            String json = new Gson().toJson(data);
            // fulfill the route with the mock data
            route.fulfill(new Route.FulfillOptions().setBody(json));
        });

and then navigate and check everything you need.

So the full example will be something like this

    @Test
    public void mockingTest() {
        Webdriver driver = new PlaywrightiumDriver();
        Page page = ((PlaywrightiumDriver)driver).getPage();
        page.route("*/**/api/v1/fruits", route -> {
            List<Dictionary<String, Object>> data = new ArrayList<>();
            Hashtable<String, Object> dict = new Hashtable<>();
            dict.put("name", "Strawberry");
            dict.put("id", 21);
            data.add(dict);
            String json = new Gson().toJson(data);
            // fulfill the route with the mock data
            route.fulfill(new Route.FulfillOptions().setBody(json));
        });
        page.navigate("https://demo.playwright.dev/api-mocking");
        assertThat(page.getByText("Strawberry").isVisible()).isTrue();
    }

britka avatar Oct 06 '24 15:10 britka