惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

H
Hackread – Cybersecurity News, Data Breaches, AI and More
C
Check Point Blog
Hacker News: Ask HN
Hacker News: Ask HN
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
WordPress大学
WordPress大学
P
Proofpoint News Feed
V
Visual Studio Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
N
Netflix TechBlog - Medium
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 聂微东
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
博客园 - 叶小钗
Cisco Talos Blog
Cisco Talos Blog
S
Schneier on Security
T
Threat Research - Cisco Blogs
腾讯CDC
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
The Hacker News
The Hacker News
Google DeepMind News
Google DeepMind News
Microsoft Security Blog
Microsoft Security Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
GbyAI
GbyAI
N
News | PayPal Newsroom
L
LINUX DO - 最新话题
酷 壳 – CoolShell
酷 壳 – CoolShell
P
Palo Alto Networks Blog
T
Tenable Blog
S
Secure Thoughts
T
Threatpost
V2EX - 技术
V2EX - 技术
大猫的无限游戏
大猫的无限游戏
Martin Fowler
Martin Fowler
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Vercel News
Vercel News
罗磊的独立博客
P
Privacy & Cybersecurity Law Blog
Engineering at Meta
Engineering at Meta
小众软件
小众软件
Google DeepMind News
Google DeepMind News
N
News and Events Feed by Topic
Y
Y Combinator Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
C
Cybersecurity and Infrastructure Security Agency CISA
P
Proofpoint News Feed
L
Lohrmann on Cybersecurity
P
Privacy International News Feed
H
Heimdal Security Blog
量子位
B
Blog

Clerk Blog

Going to production with Clerk Deploy Clerk Init: The fastest way to start a new project Introducing Clerk CLI Middleware-based route protection bypass Postmortem: Clerk System Outage (March 10, 2026) Clerk for the AI era Add API Key support to your SaaS in minutes Postmortem: Clerk System Outage (February 19, 2026) Using Clerk in a React Native app Postmortem: DNS Provider Outage (February 10, 2026) How do I implement passkeys in Next.js? Clerk ranked #4 fastest-growing software vendor on Ramp’s December 2025 list How do I handle JWT verification in Next.js? Committing to Agent Identity: Clerk raises $50m Series C from Menlo and Anthropic’s Anthology Fund What is the best way to handle authentication in Next.js App Router? Postmortem: Database Incident (September 14–18, 2025) How do I add authentication to a Next.js app? Introducing Free Trials in Clerk Billing Postmortem: August 28, 2025 - elevated API latency and errors Introducing Mosaic: Bring Your Brand to Every Authentication Flow Multi-tenant authentication: What you need to know (and how Clerk helps) What are the risks and challenges of multi-tenancy? Resilience in Practice: Regional Failover at Clerk Build a Cross-Platform B2B App with Clerk, Expo, and Supabase Highlights from the MiduDev/Clerk Hackathon Add multi-tenancy to an app built with Clerk, Lovable, and Supabase How to build an AI coding rules app with Clerk, Lovable, and Supabase How to Build Multi-Tenant Authentication with Clerk Choosing the right SaaS architecture: Multi-Tenant vs. Single-Tenant Postmortem: June 26, 2025 service outage How to Design a Multi-Tenant SaaS Architecture What is multi-tenancy and why it matters for B2B SaaS How OAuth Works Synchronize user data from Clerk to Supabase Add subscriptions to your SaaS with Clerk Billing Getting started with Clerk Billing Multi-tenant analytics with Tinybird and Clerk How Huntr Migrated 250K Users to Clerk: A Scalable Auth Solution for Startups How to take Clerk to Production How to take your Clerk application to production Implementing multi-tenancy into a Supabase app with Clerk How Clerk integrates with a Next.js application using Supabase How Clerk integrates with Supabase Build a blog with tRPC, Prisma, Next.js and Clerk How to enrich PostHog events with Clerk user data How to build a secure project management platform with Next.js, Clerk, and Neon Validate your SaaS idea while building an audience Postmortem: February 6, 2025 service outage Implement Role-Based Access Control in Next.js 15 Build a Next.js sign-up form with React Hook Form Build a Next.js login page template How to implement Google authentication in Next.js 15 What is middleware in Next.js? How to customize Next.js metadata How to set environment variables in Node.js Building a React Login Page Template How to implement per-user OAuth scopes with Clerk Using Clerk SSO to access Google Calendar and other service data Streamline enterprise customer onboarding with SAML and Clerk Clerk launches EASIE SSO and eliminates SSO fees How to secure Liveblocks Rooms with Clerk in Next.js Securing Node.js Express APIs with Clerk and React Combining the benefits of session tokens and JWTs Build a task manager with Next.js, Supabase, and Clerk Comparing Clerk Webhooks vs Backend API Automate Neon schema changes with Drizzle and GitHub Actions A guide to reading authenticated user data from Clerk Role based access control with Clerk Organizations Mitigating OAuth’s recently discovered Open Response Type vulnerability Per-user B2B monetization with Stripe and Clerk Organizations Build a team-based task manager with Next.js, Neon, and Clerk Building a Hybrid Sign-Up/Subscribe Form with Stripe Elements Welcoming Colin from Zod as our inaugural Open Source Fellow Build a modern authenticated chat application with Next.js, Ably, and Clerk Build a waitlist with Clerk user metadata How to use Clerk with PostHog Identify in Next.js How to secure API Gateway using JWT and Lambda Authorizers with Clerk What are passkeys and how do they work? Comparing Authentication in React.js vs. Next.js How to Add an Onboarding Flow for your Application with Clerk Create Your Own Custom User Menu with Radix - Part 2 Introducing Webhook Workflows with Inngest & Svix Clerk raises $30M Series B from CRV and Stripe Clerk in 2023: A Year in Review Build a Movie Emoji Quiz App with Remix, Fauna, and Clerk Ultimate Guide to Magic Link Authentication Create Your Own Custom User Menu with Radix Introducing has(), protect(), and <Protect> Updated Pricing: 10,000 MAUs Free, and a new “Pro Plan” Next.js Authentication with Clerk: Streamlined SSR Handling Clerk Webhooks: Data Sync with Convex Exploring Clerk Metadata with Stripe Webhooks The Ultimate Guide to Next.js Authentication Empower Your Support Team With User Impersonation Clerk Webhooks: Getting Started A Complete Guide to Session Management in Next.js The Advanced Guide to Passwordless Authentication in Next.js How We Roll – Chapter 10: Roundup How We Roll – Chapter 9: Infrastructure Password-Based Authentication in Next.js
A practical guide to testing Clerk Next.js applications
Lily Barrett, Alex Booker · 2025-04-11 · via Clerk Blog

We understand that writing tests isn't the most exciting part of development. That's why they are often shelved as "tech debt" or pushed to the bottom of the priority list. But it's not just about motivation - writing good tests is hard.

You might wonder:

  • What do I test?
  • How do I test it?
  • Should I write integration tests or end-to-end tests?
  • How do I mock Clerk?

This post addresses these challenges directly to help you develop a meaningful testing strategy for your Next.js application using Clerk.

By the end, you'll be equipped to test critical authentication flows by mocking Clerk's API in integration tests.

You'll also learn how to incorporate end-to-end tests and simulate real-world user interactions with your application to make sure that your application works (and continues to work) as it should in production.

Meet Pup Party

This post demonstrates how to add comprehensive tests to a sample application called Pup Party.

Pup Party allows dog owners to rate and discover dog-friendly cafes and restaurants. Users can evaluate venues as "Pup-approved" or "Pup-fail" based on criteria such as dog-friendliness, ambiance, and the quality of dog treats.

To follow along and implement tests step-by-step, download the starter code and follow the set up instructions here.

Alternatively, you can study the complete source code, including tests, here.

Choosing the right testing approach

Before we dive in, it's important to take a moment to think about what exactly you should be testing and the types of tests that will be most effective. This planning step is crucial, as it guides you in creating tests that are not only meaningful but also efficient to run and maintain.

I've seen teams fall into three common traps:

  1. Over-relying on unit tests that focus too much on internals
  2. Struggling to scale and manage integration tests effectively due to a reliance on brittle test data and overly complex test logic
  3. Over-investing in E2E tests, leading to slow, flaky test suites that bog down development

So, what's the right approach?

In this post, we turn to Kent C. Dodds and his testing trophy:

  • Write mostly integration tests
  • Supplement with well-placed E2E tests
  • Don't overdo it

Following Kent's testing philosophy, this post primarily focuses on integration tests and later addresses E2E tests for critical user paths.

Integration tests

To write integration tests, you will be using two essential tools:

  • Jest: A test runner and assertion framework to structure and execute your integration tests.
  • React Testing Library (RTL): A popular testing framework for React applications that encourages testing components from the user's perspective, while still supporting the use of Jest mocks where necessary.

Set up Jest and RTL

Start by installing these dev dependencies:

Terminal

Add a test:jest script to package.json:

./package.json

Add a jest.config.ts file to the root of your project:

./jest.config.ts

Create a jest.setup.ts file in the root of your project to globally import @testing-library/jest-dom, which enhances Jest with custom matchers for more intuitive and readable DOM assertions:

./jest.setup.ts

In the ./tsconfig.json file, add "jest" to the types array:

./tsconfig.json

Finally, create a ./__tests__ directory in your root folder. Within this directory, add an empty index.test.tsx file - this is where you'll set up your mocks, configure helpers, and write your integration tests in the next section.

Set up your mocks and helpers

In your integration tests, you should avoid making actual network calls, including to Clerk. Network calls can introduce variability and slow down your test suite, making it harder to achieve consistent and fast test results. Instead, you should mock these libraries to control their behavior in your tests and keep your integration test suite lean.

Below is the code to mock @clerk/nextjs, which allows you to simulate its behavior and focus on testing your application's logic without relying on external dependencies. Additionally, a helper function called renderWithProviders is defined. This function takes an isSignedIn argument, allowing you to simulate authenticated and unauthenticated user states in your tests.

./__tests__/index.test.tsx

Now that you have Jest and RTL configured, along with your mocks and test context provider, it's time to write some meaningful integration tests!

You will implement three integration tests for Pup Party. For each test scenario, you'll read a definition of the requirements in plain text before implementing code to programmatically test the expected behavior and protect against regressions.

Test case 1: Unauthenticated users cannot submit a review

If an unauthenticated user tries to access the submission page, they should be redirected to the sign-in page.

Here's the test implementation, along with comments explaining each notable line.

Add it to the bottom of index.test.tsx:

./__tests__/index.test.tsx

In this test, an unauthenticated user's experience on the <SubmitReviewPage /> is simulated by setting isSignedIn to false and passing it as the second argument to our renderWithProviders function.

The waitFor utility from React Testing Library is used to verify that the UI updates correctly after state changes, specifically ensuring the user is redirected to the sign-in page and cannot access the review submission content.

Test case 2: Authenticated users can successfully submit a valid review

When a signed-in user submits valid details in the review form, the form should process successfully and then display a confirmation message.

Here's the test implementation:

./__tests__/index.test.tsx

In the code above, isSignedIn is set to true to simulate the experience of an authenticated user accessing Pup Party.

The userEvent utilities are used to mimic user actions, such as clicking into a form input, typing, hitting "Submit", and viewing a success notification.

Test case 3: Authenticated users must submit valid reviews

Requirements for the submission form:

  • When authenticated users add a rating that is less than zero, they should see a "Rating must be a number above 0" error appear next to the rating field
  • When authenticated users add a written review that is less than 5 characters long, they should see a "Review must be at least 5 characters" error appear next to the review field
  • If authenticated users submit the form without correcting the errors, the form fields should retain the original values along with their error messages, and an additional "Please fix the errors in the form!" will be displayed to the user

Here's the test code that checks these requirements:

./__tests__/index.test.tsx

This code simulates a user interaction where an invalid review is submitted. It sets up a user event, renders the <SubmitReviewPage /> for an authenticated user, and then mimics user actions of submitting a valid review but an invalid rating.

The async and await syntax is used to ensure that each action and corresponding assertion happens in the correct order, as some operations are asynchronous and need to complete before the next action or assertion takes place.

Running the integration tests

Execute your integration tests by running test:jest:

Terminal

This script, defined earlier, will run the tests and display the results in your terminal:

./jest-results.png

End-to-end tests

Having implemented integration tests, let's turn our attention to end-to-end (E2E) tests.

Unlike integration tests that mock Clerk, E2E tests interact with Clerk directly to simulate production conditions.

To write E2E tests, you will be using two essential tools:

  • Playwright: A powerful automation framework that allows you to perform end-to-end testing across multiple browsers. It offers comprehensive features for simulating user interactions and validating web applications.
  • @clerk/testing: This utility offers helpful tools specifically designed for testing Clerk applications.

Set up Playwright and @clerk/testing

Start by create a new directory called ./e2e - this is where you'll write your E2E in the upcoming section.

Install @clerk/testing as a dev dependency:

Terminal

Initialize and install Playwright:

Terminal

Choose the following options when prompted:

Terminal

Replace the contents of ./playwright.config.ts to configure Playwright for end-to-end testing:

./playwright.config.ts

Define an additional script to run E2E tests:

./package.json

To ensure your E2E tests don't inadvertently run when invoking the test:jest script - which could cause errors due to Playwright tests being incompatible with Jest - update jest.config.ts as follows:

./jest.config.ts

Enable Clerk testing tokens

Clerk testing tokens allow you to bypass Clerk's bot detection mechanisms, which can otherwise block automated test requests with "bot traffic detected" errors.

The @clerk/testing library makes accessing Clerk testing tokens easy by automatically obtaining one when your test suite starts. It then offers the setupClerkTestingToken function, which injects the token, enabling your tests to bypass Clerk's bot detection mechanisms without any hassle. The clerk.signIn method internally uses the setupClerkTestingToken helper, so there's no need to call it separately when using this method.

To configure Playwright with Clerk, create ./e2e/global.setup.ts and call the clerkSetup() function:

./e2e/global.setup.ts

Next, make sure global.setup.ts is called from ./playwright.config.ts:

./playwright.config.ts

Create a test Clerk user

Since E2E tests interact with the Clerk API and require user authentication, you must create a real Clerk user and supply your test runner with the user's credentials. These credentials allow your tests to sign in, simulate an authenticated user state, and ensure everything functions as expected in a real-world scenario.

Create a test user through the Clerk dashboard:

./create-user.png

Add the username and password to .env.local. Also add your Clerk application's SECRET_KEY and PUBLISHABLE_KEY if you haven't already:

./env.local

Next, update your playwright.config.ts file to load environment variables such that they can be accessed from your tests:

./playwright.config.ts

You now have everything in place to write an end-to-end test.

Test case: Users can authenticate and successfully submit a review

This test verifies a critical user flow in a Clerk-authenticated application: signing in, submitting a review, and signing out.

Since this is an end-to-end test, it will cover multiple points in the system, ensuring that real user interactions work as expected.

Create ./e2e/user-submits-review.spec.ts and paste the following:

./e2e/user-submits-review.spec.ts

The test starts by navigating to the sign-in page and using Clerk's signIn utility to authenticate a test user.

Once signed in, the test redirects to the review submission page, where it completes and submits a form, then verifies a success message. Finally, it signs out and confirms redirection to the home page.

Running this test in the future will help catch any errors introduced by code changes. If a change breaks the functionality, the test will fail, alerting you to the issue. If the test passes, you can be confident that this flow in your application is working as it should.

Running the end-to end tests

Run test:playwright to execute your end-to-end tests:

Terminal

The result:

./playwright-results.png

Conclusion

In the introduction, key questions were posed about testing in Clerk applications:

  • What should be tested?
  • How should it be tested?
  • Should integration or end-to-end tests be used?
  • How can Clerk be effectively mocked?

This post has provided comprehensive answers to these questions, guiding you through the process of developing a robust testing strategy against a practical application.

Equipped with this knowledge, you now have the tools to confidently implement a balanced testing strategy for any appliation using Clerk for Next.js authentication.

For more detailed guidance on testing Clerk applications, be sure to check out the Clerk documentation on testing.