Pragmatic Testing in AdonisJS with Japa #7.2

Authentication in Browser Tests

In This Lesson

In this final lesson, we'll learn how to use AdonisJS Authentication with the Browser Client. We'll install and configure the Session and Auth browser plugins and visit an auth-protected page to show how it all works.

Created by
@tomgobich
Published

Finally, let's quickly cover authentication within browser tests. Similar to the API Client, the AdonisJS Auth and Session packages also provide plugins for the Browser Client. So, since we're using session authentication,n we'll want to add both the session and auth plugins.

import { sessionBrowserClient } from "@adonisjs/session/plugins/browser_client";
import { authBrowserClient } from "@adonisjs/auth/plugins/browser_client";

export const plugins: Config["plugins"] = [
  assert(),
  openapi({
    schemas: [new URL("../docs/openapi.json", import.meta.url)],
  }),
  apiClient(),
  browserClient({
    runInSuites: ["browser"],
  }),
  pluginAdonisJS(app),
  sessionApiClient(app),
  authApiClient(app),
  sessionBrowserClient(app),
  authBrowserClient(app),
  shieldApiClient(),
  disallowPinnedTests({
    disallow: !!process.env.CI,
  }),
];
Copied!
  • tests
  • bootstrap.ts

Perfect! These both add their methods to the browserContext. This provides a way to operate multiple pages with the same context so that our session or auth persists if an action taken on one page opens another page.

So, to demonstrate this, let's write a quick test to confirm that visiting the login page as an authenticated user redirects them to the home page instead.

test("redirect an authenticated user away from the login page", async ({
  visit,
  browserContext,
  route,
}) => {
  // create a user to login as
  const user = await UserFactory.create();

  // login as the user within the browserContext
  await browserContext.loginAs(user);

  // visit our page as the logged in user
  const page = await visit(route("auth.login.show"));

  // assert that we were instead redirected to the home page
  await page.assertPath("/");
});
Copied!

The loginAs method accepts a user, which is similar to our API Client; we can use our user factory to create. Once logged into the browserContext, when we visit a page, we'll be visiting that page as the logged-in user.

Alrighty, as I said, there's a ton more we could do with browser testing, but hopefully this little introduction is enough to get you up and running if it is something you're interested in. If you'd like to see more on browser testing, let me know down in the comments!

Thanks so much for watching, and happy testing!

Join the Discussion 0 comments

Create a free account to join in on the discussion
robot comment bubble

Be the first to comment!