DEV Community

Cover image for Mock /api/auth/me
Stefan Alfbo
Stefan Alfbo

Posted on

Mock /api/auth/me

Playwright is a wonderful tool for creating end-to-end tests for your web app.

The documentation is super nice and has several guides that are handy. One guide that I would like to highlight is the one about mocking APIs.

I have been using the nextjs-auth0 package in a web application that is using Auth0 as an IdP. The rate limit for requests to a tenant are pretty low when using a development tenant.

The nextjs-auth0 library makes requests to the /api/auth/me endpoint which triggers a request to the auth0 development tenant. This setup with a couple of end-to-end tests with Playwright made the requests exceeding the rate limits that was allowed on that Auth0 tenant.

To the rescue of this problem was the guide mention earlier. By using this utility function in the beforeEach setup it's possible to avoid exceeding the rate limit.

import type { Page } from '@playwright/test'
import fs from 'fs'

const meAuth0Har = './hars/me.auth0.har'

export const mockAuth0Requests = async (page: Page) => {
  const harFileExists = fs.existsSync(meAuth0Har)

  await page.routeFromHAR(meAuth0Har, {
    url: '**/api/auth/me',
    update: !harFileExists,
  })
}
Enter fullscreen mode Exit fullscreen mode

This code is based on the section Mocking with HAR files in the Playwright guide. The HAR file (HTTP Archive a JSON based format) is created automatically based on the actual network information and will be populated with real data.

With this in place the end-to-end tests stopped being flaky because of the rate limit and is now working great.

Happy hacking!

Top comments (0)