How can I stub an html response with Playwright

450 Views Asked by At

Background:

I have a react application that calls an API (getBlog) to return html to render. The html will look something like this (html is too long and proprietary to share the whole document):

enter image description here

The Problem:

I'm trying to use Playwright's page.route() and page.fulfull() methods to intercept this api call so that I can stub/mock the html response for controllable testing. I mock the html by copying the entire response (shown in the image above) into const html

I have tried intercepting 'getPosts' like so:

import { test, expect } from '@playwright/test';

const html = `<!DOCTYPE html>
...
</html>`;

test('mock response with playwright', async ({ page }) => {
  await page.route('**/getPosts', (route) => {
    route.fulfill({
      contentType: 'text/html',
      body: html,
    });
  });

  await page.goto('http://localhost.com:3000/');

  const listItem = page.getByText('Mocked Post');
  await expect(listItem).toBeVisible();
});

After the call gets intercepted, the page doesn't render most likely due to a trivial error that is hard to debug (i'm not sure what/where to find the json this error is referring to):

Expected ',' or '}' after property value in JSON at position 3075

enter image description here

The Ask:

How can I mock an api response that contains the html the react app needs to render on the page?

0

There are 0 best solutions below