3

I'm testing a server with Playwright's API testing.

I have a simple GET route, that always returns a 405 not allowed. It also logs that the API route was called. For the sake of this StackOverflow example, I replaced the log with a fetch to a place holder API.

export const loader = async () => {
  await fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(response => response.json())
    .then(json => console.log(json));
  return notAllowed();
};

In my API test, I want to intercept the fetch request to the placeholder API, and just verify that it was called, without actually calling it.

When you write a normal browser test with Playwright, you can use page.route:

page.route('*', route => {
  console.log('url', route.request().url());
  route.continue();
});

However, because this is an API test and doesn't run in a page, this won't work.

How can I intercept the API request to make assertions on it?

I tried creating a new context with:

test('my test', async ({ playwright }) => {
  const context = await playwright.request.context();
});

but that context object, is actually a request object, so you can't run request.on. I also tried using the context argument from the default fixture, but it also doesn't work.

J. Hesters
  • 13,117
  • 31
  • 133
  • 249
  • Possibly changing the default fetch function? [Intercept fetch() API requests and responses in JavaScript](https://stackoverflow.com/questions/45425169/intercept-fetch-api-requests-and-responses-in-javascript) – Flewz Nov 28 '22 at 13:35
  • Have you considered using a proxy? This seems a bit complicated for a relatively simple need, but maybe this is acceptable to you? – t.ouvre Nov 28 '22 at 14:12

1 Answers1

-1

Writing API Tests:

Playwright Test comes with the built-in request fixture that respects configuration options and can be used like below to send and assert some requests.

const { test, expect} = require('@playwright/test');


test('should get and assert an request', async ({ request }) => {
  const issues = await request.get(`https://jsonplaceholder.typicode.com/todos/1`);
  expect(issues.ok()).toBeTruthy();
  expect(await issues.json()).toEqual(expect.objectContaining({
   "userId": 1,
   "id": 1,
   "title": "delectus aut autem",
   "completed": false
  }));
});
Vishal Aggarwal
  • 1,929
  • 1
  • 13
  • 23
  • Hello Vishal, you probably misunderstood my problem. I don't want to call the placeholder API in the Playwright test. I'm calling a different API and want to assert that, as a side effect, that server that I'm testing calls the placeholder API. – J. Hesters Nov 23 '22 at 11:00
  • 1
    My Bad, I just tried to help you. – Vishal Aggarwal Nov 23 '22 at 17:00