Previously: In Setting Up Local Supabase Database Testing, we set up our workspace, module, and testing dependencies. Now let's write our first test.
With your environment configured, you're ready to write your first Supabase test. In this lesson, you'll create test files, understand the getConnections() API, and verify your setup works correctly.
Prerequisites
See Prerequisites. Requires: Complete Setting Up Local Supabase Database Testing.
Write Your First Supabase Test
Navigate back to your new supabase module:
Create a test file __tests__/basic.test.ts:
Understanding the Test Structure
The getConnections() function creates an isolated test database with:
db: APgTestClientconnected as the app-level user (typicallyanonrole)teardown(): Cleanup function that closes connections and removes the test database
The beforeEach() and afterEach() hooks provide automatic transaction rollback:
beforeEach()starts a transaction and creates a savepointafterEach()rolls back to the savepoint, ensuring test isolation
Run tests:
Expected Logs
Using Watch Mode for Rapid Testing
For faster feedback, use watch mode. First, initialize git if you haven't already:
Then run tests in watch mode:
Watch mode re-runs tests automatically when you save changes, giving you instant feedback as you develop.
Note:
pgpm initdefaults to Jest, but pgsql-test and supabase-test are test-framework agnostic—you can use it with Mocha, Vitest, or any other test runner.
Jest watch mode commands:
- Press
pto filter by filename pattern - Press
tto filter by test name pattern - Press
ato run all tests - Press
qto quit watch mode
Create a Real Schema and Test It
Now let's add a schema and table to test. Add a schema change:
Edit deploy/pets_app.sql:
Now update __tests__/basic.test.ts to test your table:
Key Takeaways
getConnections()creates an isolated test database with automatic cleanupdb.beforeEach()anddb.afterEach()provide transaction-based test isolation- Watch mode gives instant feedback during development
- Automatic rollback ensures each test starts with a clean state
- Test isolation means you can create tables, insert data, and test freely
What's Next
You've written your first Supabase test and verified your setup works. Next, you'll learn how to test Row-Level Security policies and simulate authenticated users with different roles.
