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.